samedi 25 novembre 2017

Why won't the WooCommerce Custom Checkbox remove 'attached' PHP coding, when deselected?

I am working on a WordPress eCommerce website, with the chosen shopping platform; WooCommerce.

I have created a Custom Checkbox, within the WooCommerce Product Dashboard, by placing the following code into the functions.php file:

function product_custom_fields_add(){

   global $post;

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

       echo '<div class="product_custom_field">';

    woocommerce_wp_checkbox(
        array(
            'id'        => '_engrave_text_option',
            'desc'      =>  __('set custom Engrave text field', 'woocommerce'),
            'label'     => __('Display custom Engrave text field', 'woocommerce'),
            'desc_tip'  => 'true',
            'value'     => $input_checkbox
        )
    );  

 echo '</div>';
}
add_action('woocommerce_product_options_advanced', 'product_custom_fields_add');

To save the Custom Field's values, I have inserted the following code into the functions.php file:

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

The idea is that when a Site Admin selects the Checkbox, it triggers the below code, in order to create a Custom Text Box on the Product Page:

function add_engrave_text_field() {
    global $post;

    // Get the checkbox value
    $engrave_option = get_post_meta( $post->ID, '_engrave_text_option', true );

    // If is single product page and have the "engrave text option" enabled we display the field
    if ( is_product() && ! empty($engrave_option) ) {

        ?>
        <div>
            <label class="product-custom-text-label" for="engrave_text"><?php _e( 'Custom Letters:', 'woocommerce'); ?><br>
                <input style="min-width:220px" type="text" class="product-counter" name="engrave_text" placeholder="<?php _e( 'Enter Your Custom Letters ...', 'woocommerce'); ?>" minlength="<?php global $post; echo get_post_meta($post->ID,'_minimum_engrave_text_option',true);?>" maxlength="<?php global $post; echo get_post_meta($post->ID,'_maximum_engrave_text_option',true);?>" />
            </label>
        </div><br>
<?php
    }
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_engrave_text_field', 0 );
?> 

The above code works when selecting the Checkbox, to create the Custom Text Field on the Product Page. Where the problem lies, is that when the Checkbox is deselected, the Custom Text Box remains on the Product Page.

Is anyone able to see where I am going wrong here?




Aucun commentaire:

Enregistrer un commentaire