我在 Woocommerce 管理产品数据设置中添加了一个自定义选项复选框。如果我启用该复选框并保存更改,该值将正确保存在产品元数据中,但该复选框永远不会保持选中状态。
我做错了什么?如何使它作为其他选项复选框工作?
我的代码:
function add_e_visa_product_option( $product_type_options ) {
$product_type_options[''] = array(
'id' => '_evisa',
'wrapper_class' => 'show_if_simple show_if_variable',
'label' => __( 'eVisa', 'woocommerce' ),
'description' => __( '', 'woocommerce' ),
'default' => 'no'
);
return $product_type_options;
}
add_filter( 'product_type_options', 'add_e_visa_product_option' );
function save_evisa_option_fields( $post_id ) {
$is_e_visa = isset( $_POST['_evisa'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_evisa', $is_e_visa );
}
add_action( 'woocommerce_process_product_meta_simple', 'save_evisa_option_fields' );
add_action( 'woocommerce_process_product_meta_variable', 'save_evisa_option_fields' );
最佳答案
答案很简单......你只是忘了在第一个函数中为你的数组添加一个键id,比如:
$product_type_options['evisa'] = array( // … …
所以在你的代码中:
add_filter( 'product_type_options', 'add_e_visa_product_option' );
function add_e_visa_product_option( $product_type_options ) {
$product_type_options['evisa'] = array(
'id' => '_evisa',
'wrapper_class' => 'show_if_simple show_if_variable',
'label' => __( 'eVisa', 'woocommerce' ),
'description' => __( '', 'woocommerce' ),
'default' => 'no'
);
return $product_type_options;
}
add_action( 'woocommerce_process_product_meta_simple', 'save_evisa_option_fields' );
add_action( 'woocommerce_process_product_meta_variable', 'save_evisa_option_fields' );
function save_evisa_option_fields( $post_id ) {
$is_e_visa = isset( $_POST['_evisa'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_evisa', $is_e_visa );
}
代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。
关于php - 在 Woocommerce 后端产品编辑页面中将复选框添加到产品类型选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043644/