在WooCommerce的产品库存选项卡中添加复选框,并在默认情况下选中该复选框



我在这里得到了这个片段,用来添加复选框自定义字段,它是自动设置的,运行良好。

// Displaying quantity setting fields on admin product pages
add_action( 'woocommerce_product_options_pricing', 'add_custom_field_product_options_pricing' );
function add_custom_field_product_options_pricing() {
global $product_object;
echo '</div><div class="options_group">';
$values = $product_object->get_meta('_cutom_meta_key');
woocommerce_wp_checkbox( array( // Checkbox.
'id'            => '_cutom_meta_key',
'label'         => __( 'Custom label', 'woocommerce' ),
'value'         => empty($values) ? 'yes' : $values,
'description'   => __( 'Enable this to make something.', 'woocommerce' ),
) );
}
// Save quantity setting fields values
add_action( 'woocommerce_admin_process_product_object', 'save_custom_field_product_options_pricing' );
function save_custom_field_product_options_pricing( $product ) {
$product->update_meta_data( '_cutom_meta_key', isset($_POST['_cutom_meta_key']) ? 'yes' : 'no');
}

我的问题:如何将此复选框移动到库存选项卡上,并在默认情况下选中该复选框?

我尝试过改变:

add_action( 'woocommerce_product_options_pricing', 'add_custom_field_product_options_pricing' );

至:

add_action( 'woocommerce_product_options_inventory_product_data', 'add_custom_field_product_options_pricing' );

add_action( 'woocommerce_admin_process_product_object', 'save_custom_field_product_options_pricing' );

至:

add_action( 'woocommerce_process_product_meta', 'save_custom_field_product_options_pricing' );

但无济于事。有什么建议吗?

woocommerce_admin_process_product_object替换了过时的woocommerce_process_product_meta钩子,所以您绝对不应该用它替换它

要默认选中复选框,可以将value添加到woocommerce_wp_checkbox()的参数中

所以你得到了:

// Add checkbox
function action_woocommerce_product_options_inventory_product_data() {
global $product_object;

// Get meta
$value = $product_object->get_meta( '_cutom_meta_key' );

// Checkbox
woocommerce_wp_checkbox( array( 
'id'            => '_cutom_meta_key', // Required, it's the meta_key for storing the value (is checked or not)
'label'         => __( 'Custom label', 'woocommerce' ), // Text in the editor label
'desc_tip'      => false, // true or false, show description directly or as tooltip
'description'   => __( 'Enable this to make something', 'woocommerce' ), // Provide something useful here
'value'         => empty( $value ) ? 'yes' : $value // Checked by default
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data', 10, 0 );

// Save Field
function action_woocommerce_admin_process_product_object( $product ) {
// Update meta
$product->update_meta_data( '_cutom_meta_key', isset( $_POST['_cutom_meta_key'] ) ? 'yes' : 'no' );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

最新更新