在 Woocommerce 后端产品编辑页面中将复选框添加到产品类型选项

Add checkbox to product type option in Woocommerce backend product edit pages

我在 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 文件。已测试并有效。