Save an empty value from a custom Text field in WooCommerce

余生颓废 提交于 2020-01-05 08:27:35

问题


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



来源:https://stackoverflow.com/questions/47487995/save-an-empty-value-from-a-custom-text-field-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!