WooCommerce Products Custom Fields (woocommerce)

I created a Textafield Field Type and when I put some text and hit Publish it’s displaying on my front-end. However when I remove the text to clean the front-end and click on Publish again it stays on the Textarea Field and on the front-end.
Any help please ?

Function.php

    function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  woocommerce_wp_text_input( 
    array( 
        'id'          => '_text_field', 
        'label'       => __( 'titre produit', 'woocommerce' ), 
        'placeholder' => '',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the custom value here.', 'woocommerce' ) 
    )
);


function woo_add_custom_general_fields_save( $post_id ){

    // textfield
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
    update_post_meta( $post_id, '_text_field', esc_html( $woocommerce_text_field ) );

Related posts

2 comments

  1. Simply remove this condition.

    if( !empty( $woocommerce_text_field ) )

    currently you are checking if text field not empty update the content of text field.

    When you remove above condition, it will update the field whether you put content or not.

  2. Yes you can remove the condition

    function woo_add_custom_general_fields_save( $post_id ){
    
    // textfield
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
     update_post_meta( $post_id, '_text_field', esc_html( $woocommerce_text_field ) );
    else
       update_post_meta( $post_id, '_text_field', '' );
    }
    
    **or** you can check like this also before updating or displaying: 
    
    if ( get_post_meta( $post->ID, '_text_field', true ) != '' ) {
     // your code
    }
    

Comments are closed.