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

Jua*_*vid 5 php wordpress product backend woocommerce

我在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'  );
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 8

答案很简单......你只是忘了在第一个函数中为你的数组添加一个键ID,如:

$product_type_options['evisa'] = array( // … …
Run Code Online (Sandbox Code Playgroud)

所以在你的代码中:

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 );
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的function.php文件中.经过测试和工作.

在此输入图像描述

  • @melvin你只需使用`get_post_meta($ product_id,'_ evisa',true)获取值;`变量`$ product_id`是产品ID ...(或者来自`WC_Product`对象`$ product`你可以使用: `$产品 - > get_meta( '_电子签证');`). (2认同)