Add checkbox to product type option in Woocommerce

2020-07-14 05:33发布

问题:

I have added a custom option checkbox in Woocommerce admin product data settings. If I enable that checkbox and save the changes, the value is correctly saved in product meta data, but the checkbox never stay checked.

What I am doing wrong? How to get this working as other option checkboxes?

My code:

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

回答1:

The answer is very simple… you just forgot to add a key id for your array in the first function, like:

$product_type_options['evisa'] = array( // … …

So in your code:

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 );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.