Save an empty value from a custom Text field in Wo

2019-07-23 07:15发布

问题:

I am working on a WordPress eCommerce website, with WooCommerce being the chosen Shopping Platform.

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

function product_custom_fields_add(){
echo '<div class="product_custom_field">';
    // Minimum Required Custom Letters
    woocommerce_wp_text_input(
        array(
            'id'        => '_minimum_engrave_text_option',
            'name'      => '_minimum_engrave_text_option',
            'desc'      =>  __('set custom minimum Lettering text field', 'woocommerce'),
            'label'     => __('Minimum Letters', 'woocommerce'),
            'desc_tip'  => 'true'
        )
    );
    echo '</div>';
}
add_action('woocommerce_product_options_advanced', 'product_custom_fields_add');

In order to save the values, I have entered the following code into the functions.php file:

// Save Minimum Required Custom Letters
function woocommerce_product_custom_fields_save1($post_id){
    if ( ! empty( $_POST['_minimum_engrave_text_option'] ) )
        update_post_meta($post_id, '_minimum_engrave_text_option', esc_attr( $_POST['_minimum_engrave_text_option'] ));
}
add_action( 'woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save1' );

The above code works when a value is entered into the Custom Field. My problem is that I am unable to successfully save a Blank Value. Whenever I save a Product, the Custom Field either auto populates the Field with '1' or saves a previously entered number.

I tried applying the answer, from a similar question, but could not quote get it to work.

Does anyone know where I am going wrong here?

回答1:

Try to replace empty() by isset() as a condition in the if statement of your hooked function:

// Save Minimum Required Custom Letters
function woocommerce_product_custom_fields_save1($post_id){
    if ( isset( $_POST['_minimum_engrave_text_option'] ) )
        update_post_meta($post_id, '_minimum_engrave_text_option', esc_attr( $_POST['_minimum_engrave_text_option'] ));
}
add_action( 'woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save1' );

Now this will works