Woocommerce custom fields will not be updated when I leave them empty and show empty fields

I added a custom one page product box for woocommerce to show the ISBN number for books that I sell. I found a good guide and managed to add whatever I want. However, when I empty the custom field for ISBN, it will not be empty on the site.

I have the following code in functions.php

// Display Fields add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); // Save Fields add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' ); function woo_add_custom_general_fields() { global $woocommerce, $post; echo '<div class="options_group">'; // Custom fields will be created here... // Text Field woocommerce_wp_text_input( array( 'id' => '_ISBN_field', 'label' => __( 'ISBN', 'woocommerce' ), 'placeholder' => '', 'desc_tip' => 'true', 'description' => __( 'ISBN.', 'woocommerce' ) ) ); function woo_add_custom_general_fields_save( $post_id ){ // Customer text ISBN Field $woocommerce_text_field = $_POST['_ISBN_field']; if( !empty( $woocommerce_text_field ) ) update_post_meta( $post_id, '_ISBN_field', esc_attr( $woocommerce_text_field ) ); } 

Then in short-description.php I made it appear on the product page. However, it still displays the name ISBN10: if it is an empty field.

 <?php // Display Custom Field Value if (!((get_post_meta($post->ID, '_ISBN_field', true))==")) { //Not empty echo '<b>ISBN10: </b>',get_post_meta( $post->ID, '_ISBN_field' , true); } ?> 

So, two problems: I cannot edit the product to contain an empty custom field. And if the field is empty (possible only when the field previously did not contain data), it still displays the field name.

Thanks in advance.

+2
source share
3 answers

Your save function should look like

 function woo_add_custom_general_fields_save( $post_id ){ // Customer text ISBN Field $woocommerce_text_field = $_POST['_ISBN_field']; if( !empty( $woocommerce_text_field ) ) update_post_meta( $post_id, '_ISBN_field', esc_attr( $woocommerce_text_field ) ); else update_post_meta( $post_id, '_ISBN_field', '' ); } 

If !empty( $woocommerce_text_field ) returns true only if $_POST['_ISBN_field'] has some value, so metadata is not updated if $_POST['_ISBN_field'] empty

+1
source

what is he doing:

 var_dump( get_post_meta( $post->ID, '_ISBN_field' , true) ); 

return?

I think the ist problem is that the field still contains some value, even it is empty. check that var_dump and how to configure the if statement

and I think the operator should look like this:

 if ( get_post_meta( $post->ID, '_ISBN_field', true ) != '' ) { 
0
source

Try the following:

 <?php // Display Custom Field Value $ISBN_field = get_post_meta($post->ID, '_ISBN_field', true); if( !empty( $ISBN_field ) ){ echo '<b>ISBN10: </b>'.$ISBN_field; } ?> 

Hello

0
source

Source: https://habr.com/ru/post/1269979/


All Articles