【问题标题】:Add checkbox to product type option in Woocommerce backend product edit pages在 Woocommerce 后端产品编辑页面中将复选框添加到产品类型选项
【发布时间】:2018-10-07 04:36:32
【问题描述】:

我在 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'  );

【问题讨论】:

    标签: php wordpress woocommerce backend product


    【解决方案1】:

    答案很简单……你只是忘了在第一个函数中为你的数组添加一个键 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 文件中。经过测试并且可以工作。

    【讨论】:

    • 小问题,当取消选中复选框并保存时..刷新页面仍然相同(选中)
    • @JuanDavid 对不起,但这工作得很好(在 woocommerce 版本 3.2.x 和 3.3.x 上测试过)......如果我取消选中并保存,那么复选框就会被取消选中。所以你有其他东西在那里制造麻烦。
    • 是的,对不起,我用了这个 if ( isset( $_POST['_evisa'] ) ) : ...这就是为什么没有工作,但现在我和你的代码一样......并且工作跨度>
    • 如何保存这个自定义字段,以便在前端@LoicTheAztec 中获取 $product 中的值
    • @melvin 您只需使用get_post_meta( $product_id, '_evisa', true ); 获取值,其中变量$product_id 是产品ID...(或来自WC_Product 对象$product,您可以使用:$product->get_meta('_evisa');)。
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多