• Resolved Craig1986

    (@craig1986)


    I have created a Custom Checkbox, within the Product Dashboard, using the following code in the functions.php file:

    function product_custom_fields(){
    
       global $post;
    
       $input_checkbox = get_post_meta( $post->ID, '_custom_text_option', true );
       if( empty( $input_checkbox ) || $input_checkbox == 'no' ) $input_checkbox = '';
    
        echo '<div class="product_custom_field">';
    
        woocommerce_wp_checkbox(
            array(
                'id'        => '_custom_text_option',
                'desc'      =>  __('set custom text field', 'woocommerce'),
                'label'     => __('Display custom text field', 'woocommerce'),
                'desc_tip'  => 'true',
    	    'value'     => $input_checkbox
            )
        );
    
        echo '</div>';
    }
    add_action('woocommerce_product_options_advanced', 'product_custom_fields');

    To save the values, I am using the following code:

    function woocommerce_product_custom_fields_save($post_id){
        if ( ! empty( $_POST['_custom_text_option'] ) )
            update_post_meta($post_id, '_custom_text_option', esc_attr( $_POST['_custom_text_option'] ));
    }
    add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

    For some reason, I am able to select the Checkbox and successfully save to the Product Page. Once selected, however, I am unable to deselect and successful save. When I deselect the Checkbox and select Save, the page reloads with the Checkbox still saved.

    Is anyone able to notice any errors in my above code, which could be causing this issue?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Rynald0s

    (@rynald0s)

    Automattic Happiness Engineer

    Howdy!

    Save the values like so:

    function woocommerce_product_custom_fields_save($post_id){
    	$woocommerce_wp_checkbox = isset( $_POST['_custom_text_option'] ) ? 'yes' : 'no';
      update_post_meta($post_id, '_custom_text_option', $woocommerce_wp_checkbox );
    }
    add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

    Cheers!

    Thread Starter Craig1986

    (@craig1986)

    Thanks for getting back to me.
    I have managed to resolve the issue, now. 🙂

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Cannot Save an empty Checkbox’ is closed to new replies.