wpify/custom-fields

WPify 自定义字段

安装数量: 16,801

依赖项: 2

建议者: 0

安全性: 0

星级: 5

关注者: 1

分支: 2

开放问题: 3

语言:JavaScript


README

这个库通过简单的 API 为 WordPress 和 WooCommerce 提供自定义字段。自定义字段以纯元数据形式存储,以便您可以通过标准的 WordPress 功能访问它们。前端使用 React.js 编写,没有 PHP 依赖项。该库也不包含 React 本身,而是从 WordPress 中使用 react 作为依赖项。因此,库体积小、速度快,但至少需要 WordPress 5.3。

概述

目前,您可以将自定义字段添加到以下位置

自定义字段本身使用标准的 HTML 输入,因此建议使用 Google Chrome 或 Firefox 使用自定义字段。这允许自定义字段有较小的占用空间和快速的界面。您有各种自定义字段类型可供选择

一些字段也允许多个值。您也可以通过拖放来排序值。

  • 多个附件 multi_attachment
  • 多个组 multi_group:重复器允许您在组内重复任何自定义字段。
  • 多个文章 multi_post:选择多个文章。
  • 多选 multi_select:选择多个值。

高级用法

要求

  • PHP 8.0+(我们只支持带有安全补丁的版本)
  • WordPress 6.2+(库需要React 18+,它包含在WordPress 6.2中)
  • Google Chrome/Firefox(库使用原生输入字段,只有某些浏览器支持)

开发要求

如果您想帮助开发库,请随意扩展。除了上述要求外,您还需要

  • Node 18+
  • Composer 2+

示例:自定义字段示例

以下示例向您展示了如何向页面添加自定义字段并读取数据。

  1. 通过composer在您的插件中引入库: composer require wpify/custom-fields

  2. 在您的插件中包含composer自动加载器: include_once __DIR__ . '/vendor/autoload.php';

  3. 创建一个新的带有一些文本字段的元框

wpify_custom_fields()->create_metabox( array(
   // Metabox title
   'title'      => 'Hello custom fields',
   // Array of post types that will have the custom fields
   'post_types' => array( 'page' ),
   // Array of items for the metabox
   'items'      => array( 
      // Text field
      array(
         'type'  => 'text',
         'title' => 'Text label of the meta',
         'id'    => 'some_id_of_the_meta',
      ),
   ),
) );

就是这样 :)

实现

如何向文章类型添加自定义字段?

Adding a metabox to the post

上述示例展示了如何添加元框的最简示例。让我们通过完整的选项列表来扩展它。在上面的代码片段中,您可以看到所有选项及其默认值。

wpify_custom_fields()->create_metabox( array(
   'id'            => null,
   'title'         => null,
   'screen'        => null,
   'context'       => 'advanced',
   'priority'      => 'default',
   'callback_args' => null,
   'items'         => array(),
   'post_types'    => array(),
   'display'       => function() {
	  // Conditional display
	  return true;
   },
) );

参数

  • idtitlescreencontextprioritycallback_args:请参阅add_meta_box函数的WordPress文档。
  • items:数组,必需:元框中的自定义字段列表。
  • post_types:数组,必需:具有自定义字段的文章类型列表。

请注意,要使文章类型具有自定义字段。对于自定义文章类型,在register_post_type函数中的supports数组中添加custom-fields,或使用add_post_type_support函数将支持添加到某些现有文章类型。

读取自定义字段

要读取数据,您可以使用简单的内置函数。

$some_custom_field_value = get_post_meta( $post_id, 'some_id_of_the_meta', true );

链接

如何向分类法术语添加自定义字段?

Taxonomy custom fields

该功能在添加和编辑分类术语的界面都添加了元框。

wpify_custom_fields()->create_taxonomy_options( array(
   'taxonomy' => null,
   'items'    => array(),
   'display'  => function() {
	  // Conditional display
	  return true;
   },
) );

参数

  • taxonomy 字符串,必填。要添加自定义字段的分类,例如,对于文章分类使用 category,对于 WooCommerce 产品分类使用 product_cat
  • items:数组,必填:术语中的自定义字段列表。

读取自定义字段

要读取数据,您可以使用简单的内置函数。

$some_custom_field_value = get_term_meta( $term_id, 'some_id_of_the_meta', true );

链接

  • get_term_meta:[https://developer.wordpress.org/reference/functions/get_term_meta/](https://developer.wordpress.org/reference/functions/get_term_meta/)

如何创建带有自定义字段的选项页面?

Options page

使用这个库,您可以在顶部或二级位置轻松地创建选项页面。底层使用 add_menu_pageadd_submenu_page 核心函数。

wpify_custom_fields()->create_options_page( array(
   'type'        => 'normal',
   'parent_slug' => null,
   'page_title'  => '',
   'menu_title'  => '',
   'capability'  => 'manage_options',
   'menu_slug'   => null,
   'icon_url'    => null,
   'position'    => null,
   'items'       => array(),
   'display'     => function() {
	  // Conditional display
	  return true;
   },
) );

参数

  • type:目前唯一允许的值是 normal(标准选项页面)。
  • parent_slug:如果选项页面是顶级页面,请留空。如果要将页面添加到二级,请在此处添加顶级页面的 slug,例如:
    • index.php 用于仪表板,
    • edit.php 用于文章,
    • upload.php 用于媒体,
    • edit.php?post_type=page 用于页面,
    • edit-comments.php 用于评论,
    • edit.php?post_type=your_post_type 用于您自定义的文章类型,
    • themes.php 用于外观,
    • plugins.php 用于插件,
    • users.php 用于用户,
    • tools.php 用于工具,
    • options-general.php 用于设置,
    • settings.php 用于网络设置,
    • woocommerce 用于 WooCommerce,
    • 或任何您的自定义顶级菜单 slug。
  • page_title:设置页面的标题。
  • menu_title:菜单中的设置页面标题。
  • capability:用户查看页面所需的权限。
  • menu_slug:页面的唯一菜单 slug。
  • icon_url:顶级菜单的图标。请参阅 add_menu_page 的文档以了解如何添加菜单图标。
  • position:顶级菜单页面的位置。请参阅 add_menu_page 的文档。
  • items:数组,必填:选项中的自定义字段列表。

读取自定义字段

$some_custom_field_value = get_option( 'some_id_of_the_option' );

链接

  • add_submenu_page:[https://developer.wordpress.org/reference/functions/add_submenu_page/](https://developer.wordpress.org/reference/functions/add_submenu_page/)
  • add_menu_page:[https://developer.wordpress.org/reference/functions/add_menu_page/](https://developer.wordpress.org/reference/functions/add_menu_page/)
  • get_option:[https://developer.wordpress.org/reference/functions/get_option/](https://developer.wordpress.org/reference/functions/get_option/)

如何将自定义字段添加到 WooCommerce 设置中?

WooCommerce settings

如果想要轻松地将设置选项卡或部分添加到 WooCommerce → 设置,可以使用以下代码片段

wpify_custom_fields()->create_woocommerce_settings( array(
   'tab'     => array( 'id' => '', 'label' => null ),
   'section' => array( 'id' => '', 'label' => null ),
   'items'   => array(),
   'display' => function() {
	  // Conditional display
	  return true;
   },
) );

参数

  • tab:选项卡的标识。请提供一个包含 idlabel 键的数组。如果选项卡不存在,它将被创建。
  • section:部分的标识。请提供一个包含 idlabel 键的数组。如果部分不存在,它将被创建。
  • items:数组,必填:设置中的自定义字段列表。

读取设置字段

WooCommerce 设置存储为标准选项,您可以按照以下方式读取

$some_custom_field_value = get_option( 'some_id_of_the_option' );

链接

  • get_option:[https://developer.wordpress.org/reference/functions/get_option/](https://developer.wordpress.org/reference/functions/get_option/)

如何将自定义字段添加到产品选项中?

Product options

产品选项是放置自定义字段的绝佳位置。您可以定义如下

wpify_custom_fields()->create_product_options( array(
   'tab'          => array(
      'id'       => 'general',
      'label'    => null,
      'priority' => 100,
      'class'    => array(),
   ),
   'init_priority' => 10,
   'display'       => function() {
	  // Conditional display
	  return true;
   },
   'items'         => array(),
) );

参数

  • tab:带有选项卡的数组。如果选项卡 ID 不存在,它将被创建。
    • id:选项卡的 ID。
    • label:选项卡的标签。
    • priority:选项卡的优先级。
    • class:选项卡的类。您可以使用任何类,但也可以使用一些内置类:hide_if_groupedshow_if_simpleshow_if_variableshow_if_groupedshow_if_externalhide_if_externalhide_if_virtual
  • items:数组,必填:选项中的自定义字段列表。

读取自定义字段

产品选项以文章元数据的形式存储,因此您可以像读取其他任何文章元数据一样读取这些数据。

$some_custom_field_value = get_post_meta( $product_id, 'some_id_of_the_meta', true );

链接

如何在使用HPOS的情况下向WooCommerce订单添加自定义字段?

Order metabox

使用订单元数据框将元数据框添加到已启用HPOS的WooCommerce订单中。您可以按以下方式定义:

$this->wcf->create_order_metabox(
	array(
		'title'      => 'Details',
		'items' => array(
			array(
				'type'  => 'text',
				'id'    => 'test',
				'title' => 'Test',
			),
		),
	)
);

参数 请参阅create_metabox参数。

读取自定义字段

订单元数据使用标准的WooCommerce CRUD函数进行存储,因此您可以像读取其他任何订单元数据一样读取这些数据。

$order = wc_get_order( $order_id );
$order->get_meta( 'test' );

链接

如何向产品变体添加自定义字段?

Product options

您也可以向产品变体添加自定义字段。您可以按以下方式定义:

wpify_custom_fields()->create_product_variation_options( array(
   'after'          => 'pricing',
   'init_priority' => 10,
   'display'       => function() {
	  // Conditional display
	  return true;
   },
   'items'         => array(),
) );

参数

  • after:您想要放置自定义字段的项之后的位置。可能的选项有:pricing(默认),inventorydimensionsdownloadattributes(在所有字段之后)。
  • items:数组,必填:选项中的自定义字段列表。

读取自定义字段

产品选项以文章元数据的形式存储,因此您可以像读取其他任何文章元数据一样读取这些数据。

$some_custom_field_value = get_post_meta( $product_variation_id, 'some_id_of_the_meta', true );

链接

如何向会员计划选项添加自定义字段?

Membership plan options

WooCommerce会员计划选项与产品选项类似。您可以按以下方式定义:

wpify_custom_fields()->create_membership_plan_options( array(
   'tab'          => array(
      'id'       => 'general',
      'label'    => null,
      'priority' => 100,
      'class'    => array(),
   ),
   'init_priority' => 10,
   'display'       => function() {
	  // Conditional display
	  return true;
   },
   'items'         => array(),
) );

参数

  • tab:带有选项卡的数组。如果选项卡 ID 不存在,它将被创建。
    • id:选项卡的 ID。
    • label:选项卡的标签。
    • priority:选项卡的优先级。
    • class:选项卡的类。您可以使用任何类,但也可以使用一些内置类:hide_if_groupedshow_if_simpleshow_if_variableshow_if_groupedshow_if_externalhide_if_externalhide_if_virtual
  • items:数组,必填:选项中的自定义字段列表。

读取自定义字段

会员计划选项以文章元数据的形式存储,因此您可以像读取其他任何文章元数据一样读取这些数据。

$some_custom_field_value = get_post_meta( $membership_plan_id, 'some_id_of_the_meta', true );

链接

如何生成带有自定义字段的Gutenberg块?

Gutenberg Block

您可以轻松生成将使用自定义字段界面的块。如果您想用您自己的替换默认自定义字段界面,只需将editor_scripteditor_style属性设置为已注册脚本和样式的处理程序即可。每个已注册的块都有一个包含在块中使用的自定义字段定义的wcf属性。

wpify_custom_fields()->create_gutenberg_block( array(
	'name'             => null, // string
	'title'            => null, // string
	'category'         => 'common', // string
	'parent'           => null, // string
	'icon'             => null, // string
	'description'      => null, // string
	'keywords'         => array(), // array
	'textdomain'       => null, // string
	'styles'           => array(), // array
	'supports'         => null, // array
	'example'          => null, // array
	'render_callback'  => null, // callable
	'attributes'       => array(), // array
	'uses_context'     => array(), // array
	'provides_context' => null, // array
	'editor_script'    => null, // string
	'script'           => null, // string
	'editor_style'     => null, // string
	'style'            => null, // string
	'items'            => array(), // array
    'display'          => function() {
	  // Conditional display
	  return true;
   },
) );

参数

  • name:必需的块名称,格式为namespace/block-name
  • titlecategoryparenticondescriptionkeywordstextdomainstylessupportsexamplerender_callbackattributesuses_contextprovides_contexteditor_scriptscripteditor_stylestyle属性是register_block_type函数中描述的参数。
  • items:必需的数组:选项中自定义字段的列表。

将属性移至侧边栏

如果您想将特定属性从块移动到侧边栏,请向项目添加选项'position' => 'inspector'

链接

示例

wpify_custom_fields()->create_gutenberg_block( array(
	'name'        => 'wcf/test',
	'title'       => 'Test block',
	'items'       => array(
		array(
			'type'        => 'text',
			'title'       => 'Example text',
			'id'          => 'some_example_text',
			'description' => 'and example description',
			'label'       => 'with example label',
		),
		array(
			'type'        => 'text',
			'title'       => 'Example text 2',
			'id'          => 'some_example_text_2',
			'description' => 'and example description',
			'label'       => 'with example label',
			'position'    => 'inspector',
		),
	),
	'render_callback' => function ( $attributes ) {
		return '<h2>' . $attributes['some_example_text'] . '</h2><p>' . $attributes['some_example_text'] . '</p>';
	},
) );

如何向用户添加自定义字段?

该功能向用户添加选项

wpify_custom_fields()->create_user_options( array(
   'items'    => array(),
) );

参数

  • items:数组,必填:术语中的自定义字段列表。

读取自定义字段

要读取数据,您可以使用简单的内置函数。

$some_custom_field_value = get_user_meta( $user_id, 'some_id_of_the_meta', true );

链接

如何向评论添加自定义字段?

Adding a metabox to the post

您也可以轻松地向评论添加自定义字段

wpify_custom_fields()->create_comment_metabox( array(
   'id'    => 'cool_comments_metabox',
	'title' => __( 'Example metabox', '' ),
	'items' => array(
		array(
			'type'  => 'text',
			'id'    => 'test',
			'label' => 'Test metafield'
		),
	),
) );

参数

有关可用参数,请参阅文章元数据。

读取自定义字段

要读取数据,您可以使用简单的内置函数。

$some_custom_field_value = get_comment_meta( $post_id, 'some_id_of_the_meta', true );

链接

自定义字段定义

在上面的示例中,只显示了一个自定义字段。但您不仅可以定义文本字段。有许多字段类型可供使用。所有字段都具有以下一些共同属性。

$some_item = array(
   'type'              => '',
   'id'                => '',
   'title'             => '',
   'placeholder'       => '',
   'suffix'            => '',
   'custom_attributes' => array(),
   'description'       => '',
   'display'           => function ( $item, $context ) {
        return true;
   },
);

// Some dummy usage, use `add_*` methods listed above.
wpify_custom_fields()->add_some_custom_field_implementation( array(
   // some options
   'items'    => array( $some_item ),
) );

常见属性

  • type:字段类型标识,例如textdateattachment
  • id:项目的唯一ID。此ID将被直接用作元字段的名称。
  • title:用作字段标签的标题。
  • placeholder:如果未填写值时将显示的占位符。
  • suffix:字段后面的文本。
  • custom_attributes:您想要添加到字段的自定义属性数组。
  • description:将显示在字段下方的描述。
  • display:回调函数或布尔值,指示项目是否显示。

附件字段类型 attachmentmulti_attachment

Attachment field type

其他属性

  • attachment_type:可选的附件类型。例如,可以是 imageimage/png 等。

复选框字段类型 checkbox

Checkbox field type

其他属性

  • label:复选框后面的可选标签。

代码编辑器字段类型 code

Code field type

其他属性

  • mode:代码编辑器的模式,用于高亮显示,例如 cssjavascripthtmlphpmarkdown 等。

颜色字段类型 color

Color field type

日期字段类型 date

Date field type

日期和时间字段类型 datetime

Date and time field type

电子邮件字段类型 email

E-mail field type

分组字段类型 groupmulti_group

单个分组 group

分组字段没有任何视觉表示,但将字段分组到一个字段中。以下是在选项页面中定义分组字段的示例

wpify_custom_fields()->create_options_page( array(
   'id'          => 'example_options_page',
   'page_title'  => 'Hello custom fields',
   'menu_title'  => 'Hello WCF',
   'menu_slug'   => 'hello-wcf',
   'position'    => 1000,
   'items'       => array(
      array(
         'id'              => 'some_example_group',
         'type'            => 'group',
         'title'           => 'Group',
         'items'           => array(
            array(
               'type'            => 'text',
               'title'           => 'Text in group 1',
               'id'              => 'some_example_text_1',
            ),
            array(
               'type'            => 'text',
               'title'           => 'Text in group 2',
               'id'              => 'some_example_text_2',
            ),
         )
      ),
   ),
) );

结果如下

Group field;

现在我们可以设置一些值并访问数据

$value = get_option('some_example_group');

上面的代码将生成以下数组

array(
  "some_example_text_1" => "Some value 1",
  "some_example_text_2" => "Some value 2",
);

分组还可以嵌套,以获取比上述示例更复杂的数据结构。

重复分组 multi_group

如果我们把上面的字段类型改为 multi_group,我们将得到不同的结果

wpify_custom_fields()->create_options_page( array(
   'id'          => 'example_options_page',
   'page_title'  => 'Hello custom fields',
   'menu_title'  => 'Hello WCF',
   'menu_slug'   => 'hello-wcf',
   'position'    => 1000,
   'items'       => array(
      array(
         'id'              => 'some_example_group',
         'type'            => 'multi_group',
         'title'           => 'Multi group',
         'items'           => array(
            array(
               'type'            => 'text',
               'title'           => 'Text in group 1',
               'id'              => 'some_example_text_1',
            ),
            array(
               'type'            => 'text',
               'title'           => 'Text in group 2',
               'id'              => 'some_example_text_2',
            ),
         )
      ),
   ),
) );

Multi group field

自定义字段的值如下

array(
    array(
        "some_example_text_1" => "Some text 1",
        "some_example_text_2" => "Some value 2",   
    ),
    array(
        "some_example_text_1" => "Some text 2",
        "some_example_text_2" => "",   
    ),
);

如您所见,您可以在内部添加任何字段的新组,通过拖放移动组,并删除组项目。

其他属性

  • items:包含组内部字段的数组。
  • min:int,项目的最小数量。
  • max:int,项目的最大数量。
  • disable_buttons:数组,禁用多组按钮(add|delete|duplicate|move)。
  • buttons:数组,自定义按钮的标签;按钮类型作为键(add|delete|duplicate|move)和自定义文本作为值。
  • group_title:string,组内字段ID,用作组标题。

HTML字段类型 html

HTML Field

其他属性

  • content:要渲染的HTML字符串。

内部块字段类型 inner_blocks

内部块的使用有限,请遵循

  • 仅适用于Gutenberg块。
  • 不能用于分组。
  • 在块中只能使用一个 inner_blocks 字段。

其他属性

  • template:要渲染的HTML字符串。

链接字段类型 link

返回数组的字段 array( 'url' => '', 'label' => '', 'target' => null, 'post' => null )

其他属性

  • post_type:您想链接到的帖子类型的名称。

Mapy.cz 字段类型 mapycz

显示位置和地图的搜索框,用户可以设置一些位置。输出是一个具有以下形状的对象

{
  "address": "Praha",
  "latitude": 50.0835493857,
  "longitude": 14.4341412988,
  "zoom": 12
}

月份字段类型 month

Month field

数字字段类型 number

Number field

密码字段类型 password

Password field

帖子字段类型 postmulti_post

Post field Post field

允许从特定帖子类型中选择帖子。

其他属性

  • string post_type
  • array query_args
  • bool async

选择字段类型 selectmulti_select

Select field

选择字段可以异步从API(推荐)或从 option 属性内联接收选项。每个选项都必须是一个具有 labelvalue 键的关联数组。

其他属性

  • options 选项列表或返回具有 valuelabel 键的选项列表的回调。或者,您可以使用具有值作为键和标签作为值的关联数组。
  • async 如果为真,选项列表将异步加载。
  • array async_params 异步请求的附加GET参数。

示例

$field = array(
	'id'      => 'some_id_of_field',
	'type'    => 'select',
	'label'   => __( 'Example select', 'your_plugin' ),
	'options' => array(
		3 => 'Test 3',
		2 => 'Test 2',
		1 => 'Test 1',
		0 => 'Test 0',
	),
);

// OR

$field = array(
	'id'      => 'some_id_of_field',
	'type'    => 'select',
	'label'   => __( 'Example select', 'your_plugin' ),
	'options' => array(
		array( 'value' => 3, 'label' => 'Test 3' ),
		array( 'value' => 2, 'label' => 'Test 2' ),
		array( 'value' => 1, 'label' => 'Test 1' ),
		array( 'value' => 0, 'label' => 'Test 0' ),
	),
);

// OR

$field = array(
	'id'      => 'some_id_of_field',
	'type'    => 'select',
	'label'   => __( 'Example select', 'your_plugin' ),
	'options' => 'callback_that_returns_options_in_shape_as_above',
);

电话号码字段类型 tel

Tel field

其他属性

  • initial_country 初始选择的国家。

多行文本字段类型 textarea

Textarea field

文本字段类型 text

Text field

时间字段类型 time

Time field

标题字段类型 title

Title field

切换字段类型 toggle

Toggle field

其他属性

  • label 切换后的标签

URL字段类型 url

URL field

周字段类型 week

Week field

所见即所得字段类型 wysiwyg

此字段为您提供了TinyMCE编辑器,允许您可视化地编辑HTML!

WYSIWYG field

其他属性

  • toolbar 工具栏中的按钮字符串。如果您在具有编辑器的页面上打开开发者控制台并输入 window.wpEditorL10n.tinymce.settings.toolbar1,则可以查看默认选项。

扩展字段类型

您可以通过自己的来扩展自定义字段类型

  1. 使用字段创建React组件
import React, { useState } from 'react';

const MyCustomField = (props) => {
   const { id, className, group_level = 0, value } = props;
   const [currentValue, setCurrentValue] = useState(value);
   
   return (
     <React.Fragment>
      {group_level === 0 && ( // We need to have the input with the name only if not in group
        <input type="hidden" name={id} value={currentValue}/>
      )} 
      <input
         id={id}
         type="text"
         className={classnames('regular-text', className)}
         onChange={(e) => setCurrentValue(e.target.value)}
         value={currentValue}
      />
     </React.Fragment>
   );
};

export default MyCustomField;
  1. 注册字段
import { addFilter } from '@wordpress/hooks';
import { MyCustomField } from './fields/MyCustomField.js';
const type = 'my_custom_field';
addFilter('wcf_field_' + type, 'my-plugin-slug', Component => MyCustomField);
  1. 注册解析器和净化器(如有必要)

请参阅 src/Parser.phpsrc/Sanitizer.php 中的代码,以获取过滤器。

Bedrock支持

如果您使用Bedrock,则默认情况下自定义字段不会工作,因为供应商文件夹位于docroot之外,而WCF所需资产位于供应商文件夹中。此解决方案是将WCF移至文档根目录。要启用此功能,请require "mnsami/composer-custom-directory-installer",该插件允许将特定包安装到另一个位置

composer require mnsami/composer-custom-directory-installer

之后,您可以在您的 composer.json 中指定位置

{
  ...
  "extra": {
    "installer-paths": {
      ... 
      "web/app/vendor/{$vendor}/{$name}": [
        "wpify/custom-fields"
      ]
    },
    ...
  }
  ...
}

运行 composer update,WCF将安装到 web/app/vendor/wpify/custom-fields 文件夹中。然后,您可以按照以下方式初始化WCF

$custom_fields = new CustomFields( content_url( '/app/vendor/wpify/custom-fields' ) );

高级用法 - 条件自定义字段

您可以根据数据自定义自定义字段。例如,当用户选择白色时,您想显示背景颜色字段。这要归功于前端上的过滤器,您可以在JavaScript中定义以下内容

import { addFilter } from '@wordpress/hooks';

addFilter('wcf_definition', 'my-plugin-test', (wcf, data) => {
  // Define when to apply filters wery carefully, if you don't want to mess with bugs!
  if (wcf.object_type === 'options_page' && wcf.menu_slug === 'some-test-menu-slug') {
		// Remove the an conditional field if present.
		const newItems = wcf.items.filter(i => i.id !== 'some_background_color');

		// If some_color is white, insert the conditional field after field ID "some_color".
		if (data.some_color === '#ffffff') {
      		// Find an index of "some_color" field.
			const index = newItems.map(i => i.id).indexOf('some_color');

      		// Insert new field after "some_color" field.
			newItems.splice(index + 1, 0, {
				id: 'some_background_color',
				title: 'Background color',
				type: 'color',
				value: data.some_background_color || '',
			});
		}

		// Return new WCF definition.
		return {
			...wcf,
			items: newItems,
		};
  }
  
  // By default, return the original WCF definition.
  return wcf;
});

此方法有一些注意事项

  • 您不能在多组字段类型中定义条件字段。新项目将应用于多组中的所有组。
  • 如果在gutenberg块中定义条件,则需要定义所有属性,否则不会保存。

您还可以使用过滤器 wcf_field_props,允许您修改例如字段的类名。

import { addFilter } from '@wordpress/hooks';

addFilter('wcf_field_props', 'my-plugin-test', (props) => {
  if (props.appContext.object_type === 'options_page' && props.appContext.menu_slug === 'some-test-menu-slug' && props.id === 'test_field') {
		props.className += ' test-class';
  }
  
  return props;
});

上面的代码将向ID为 test_field 的字段添加 test-class,该字段位于具有slug some-test-menu-slug 的选项页上。

高级用法 - 自定义获取器和设置器

如果您想从/到非默认位置检索或保存字段值,可以轻松地使用 callback_getcallback_set 参数覆盖获取器和设置器。

参数

  • callback_get:回调函数,它将接收字段定义 $item 和对象ID $id,并应返回字段值
  • callback_set:回调函数,它将接收字段定义 $item、对象ID $id 和字段值 $value

以下示例演示了使用 get_optionupdate_option 函数保存和检索帖子元字段。

wpify_custom_fields()->create_metabox( array(
	'title'      => 'Details',
	'post_types' => array( 'post' ),
	'priority' => 'high',
	'items'      => array(
		array(
			'type'  => 'text',
			'title' => 'Some field',
			'id'    => 'some_field',
			'callback_get' => function($item, $id) {
				// Retrieve the value from wp_options. 
				return get_option($item['id'],'');
			},
			'callback_set' => function($item, $id, $value) {
				// Save the value to wp_options.
				update_option($item['id'],$value);
			},
			),
		),
	) 
);