-1

The intention of my PHP code below is to display the product GTIN number when it is available and display a message when it isn't. But regardless of whether or not a GTIN value exists, it just returns the message.

// https://businessbloomer.com/woocommerce-add-text-add-cart-single-product-page/   
add_action( 'woocommerce_single_product_summary', 'custom_data_above_add_to_cart_button', 6 );
function custom_data_above_add_to_cart_button( $product ) {

// https://wordpress.stackexchange.com/a/165757/135006
      if ( get_post_meta( $post->ID, 'wccaf_gtin', true ) ) {

        echo '<p>'.get_post_meta( $post->ID, 'wccaf_gtin', true ).'</p>';

    } else {

        echo '<p>GTIN unspecified.</p>';

    }
}
phrogg
  • 888
  • 1
  • 13
  • 28
  • Use `$product->get_id()` instead of `$post->ID`. If you have an older version of wordpress you have to use `$product->id` or a btter solution would be to update the plugin. Since get_id() function is available from version 2.6.0 – Omar Tanti Mar 23 '18 at 06:14
  • It just stalls when I try to load the product page now? –  Mar 23 '18 at 06:18
  • What woocommerce version do you have installed? Or else what you can do is add `global $post;` at the very beginning of the function – Omar Tanti Mar 23 '18 at 06:19
  • I tried a variation of your solution: `$product->id`, product page now loads fine but again, the message displays rather than the value. –  Mar 23 '18 at 06:20
  • Are you sure the meta key **wccaf_gtin** is correct? – Omar Tanti Mar 23 '18 at 06:21
  • @Omar Tanti Version 3.3.4 –  Mar 23 '18 at 06:21
  • @Omar Tanti How can I check if the meta key is correct? –  Mar 23 '18 at 06:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167392/discussion-between-omar-tanti-and-user136649). – Omar Tanti Mar 23 '18 at 06:26

1 Answers1

-1

Use like this.

add_action('woocommerce_single_product_summary', function($product){
if ( get_post_meta( $product->get_id(), 'wccaf_gtin', true ) ) {
    echo '<p>'.get_post_meta( $product->get_id(), 'wccaf_gtin', true ).'</p>';
} else {
    echo '<p>GTIN unspecified.</p>';
}
}, 6, 1);