Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'  );
like image 826
Juan David Avatar asked Apr 26 '18 12:04

Juan David


1 Answers

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.

enter image description here

like image 184
LoicTheAztec Avatar answered Sep 28 '22 03:09

LoicTheAztec