Woocommerce中管理员编辑产品的复选框自定义字段

Bog*_*dan 2 wordpress checkbox product woocommerce hook-woocommerce

我正在尝试将复选框添加到 WooCommerce(在管理面板中)的设置选项卡并使用以下代码:

add_action( 'woocommerce_product_options_general_product_data', 'wc_custom_add_custom_fields' );
function wc_custom_add_custom_fields() {    
    global $post;
    woocommerce_wp_checkbox(array( 
        'id'            => 'is_gift', 
        'label'         => __('Gift', 'woocommerce' ), 
        'description'   => __( 'Add gift label', 'woocommerce' ),
        'value'         => get_post_meta($post->ID, 'is_gift', true) 
    ));
}

add_action( 'woocommerce_process_product_meta', 'wc_custom_save_custom_fields' );
function wc_custom_save_custom_fields() {
    global $post;
    if (!empty($_POST['is_gift'])) {
        update_post_meta( $post->ID, 'is_gift', esc_attr( $_POST['is_gift'] ) );       
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码显示复选框,但不保存更改。它仅适用于一种产品。我猜有什么问题$post->ID吗?

Loi*_*tec 5

更新……试试这个:

add_action( 'woocommerce_product_options_general_product_data', 'wc_custom_add_custom_fields' );
function wc_custom_add_custom_fields() {
    global $post;

   $input_checkbox = get_post_meta( $post->ID, 'is_gift', true );
   if( empty( $input_checkbox ) ) $input_checkbox = '';

    woocommerce_wp_checkbox(array(
        'id'            => 'is_gift',
        'label'         => __('Gift', 'woocommerce' ),
        'description'   => __( 'Add gift label', 'woocommerce' ),
        'value'         => $input_checkbox,
    ));
}

add_action( 'woocommerce_process_product_meta', 'wc_custom_save_custom_fields' );
function wc_custom_save_custom_fields($post_id) {
    $_custom_text_option = isset( $_POST['is_gift'] ) ? 'yes' : '';
    update_post_meta( $post_id, 'is_gift', $_custom_text_option );
}
Run Code Online (Sandbox Code Playgroud)

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