WooCommerce 后台自定义产品选项(2021)
WooCommerce 如何增加自定义产品选项?产品编辑页面( Product Metabox )是WordPress Metabox。本文先介绍一个增加自定义产品字段的代码示例,再给出各个位置的钩子函数,最后介绍如何从前台获取自定义产品选项。

自定义产品选项的代码
目标是在上图所示的常规
选项卡下添加一个自定义字段,代码如下,放在子主题的functions.php
里。
/**
* 增加自定义字段
*/
add_action( 'woocommerce_product_options_general_product_data', function(){
$product = wc_get_product();
woocommerce_wp_select(
array(
'id' => '_my_custom_field',
'value' => get_post_meta($product->get_id(), '_my_custom_field',true),
'label' => 'Custom Field',
'options' => array('1' => 'option 1', '2' => 'option 2'),
'desc_tip' => 'true',
'description' => 'A custom field',
)
);
});
/**
* 保存自定义字段的值
*/
add_action('woocommerce_process_product_meta', function( $post_id ) {
$product = wc_get_product($post_id);
$custom_field_value = $_POST['_my_custom_field'] ?? '';
$product->update_meta_data('_my_custom_field', sanitize_text_field($custom_field_value) );
$product->save();
});
可用的actions
如果要在其它选项卡下添加,请把 woocommerce_product_options_general_product_data
这个action换成对应的,每个选项卡都有自己的action,如下所示:
- 常规 – woocommerce_product_options_general_product_data
- 库存 – woocommerce_product_options_inventory_product_data
- 配送 – woocommerce_product_options_shipping
- 连锁产品 – woocommerce_product_options_related
- 属性 – woocommerce_product_options_attributes
- 高级 – woocommerce_product_options_advanced
上面这些是通用action,不论什么产品类型。还有一些action是针对特定产品类型+特定位置的,为了清晰的表述位置,sola将以图片的方式展示给大家,文字标识了这些action会出现的位置。
常规 / General选项卡下
woocommerce_product_options_external

woocommerce_product_options_pricing

woocommerce_product_options_downloads

woocommerce_product_options_tax

配送 / Shipping选项卡下
woocommerce_product_options_dimensions

库存 / Inventory选项卡下
woocommerce_product_options_sku

woocommerce_product_options_stock

woocommerce_product_options_stock_fields

woocommerce_product_options_stock_status

woocommerce_product_options_sold_individually

连锁产品 / Linked Products
woocommerce_product_options_related

属性 / Attributes
woocommerce_product_options_attributes

高级 / Advanced
woocommerce_product_options_reviews

在前台如何获取
这些自定义字段以post meta的形式存在,所以用get_post_meta()函数就可以了。