2

I'm creating a plugin to display schema script for my WooCommerce product. I use a custom field to add my gtin number in WooCommerce.

This is what I did:

<?php
    $gtin = get_post_meta(post_ID,'gtin',true);
?>
<script type="application/ld+json">{
    "gtin13:"<?php echo $gtin;?>"</script>}

The result:

"gtin13:"1112223334"

Which work fine…

But sometime products doesn't have gtin number, so I created function like this:

  1. go check if there is gtin number or not?
  2. If don't echo "identifier_exit:false"
  3. If found gtin number echo "gtin13:gtin number"
     <?php
         function check_gtin() {
             $gtin=get_post_meta(post_ID,'gtin',true);
             if ($gtin!='') {
                 echo '$gtin13:$gtin';
             } else {
                 echo 'identifier_exits:false';
             }
         }
     ?>
    <script type="application/json+ld">{
        "<?php check_gtin();?>"</script>}

The result:

"gtin13:$gtin"

What I am expecting:

"gtin13:1112223334"

So can someone point to me what I did wrong?

1

There are some errors as get_post_meta() first argument need to be a defined product ID here (and in your code post_ID is not even dynamic variable and will not give anything)…

Try the following:

<?php
     function check_gtin(){
         if ( $gtin = get_post_meta(get_the_id(), 'gtin', true) ){
             echo "gtin13:". $gtin;
         } else {
             echo 'identifier_exits:false';
         }
     }
 ?>

Then:

<script type="application/json+ld">{"<?php check_gtin(); ?>"</script>

It should better work…

0

One problem is that you need to pass the $post_id to the function so it has something to work with.

global $post;

check_gtin( $post->ID );

function check_gtin( $post_id ) { /* ... */ }

Another problem is that in PHP single quotes are meant to be literal strings and will not print the variables in them. There's a couple ways to convert this into working code:

Double Quotes

echo "gtin13:{$gtin}";

String Concatenation

echo 'gtin13:' . $gtin;

Formatted Printing

printf( 'gtin13:%s', $gtin );

Additionally, depending on how you're setting the post meta it could return something "empty" but not necessary an empty string ''. Personally, I prefer to use empty() to check if something exists. This will check for empty arrays, empty strings, 0, false.


To bring it altogether, it could look like:

/**
 * Display GTIN
 *
 * @param Integer $post_id
 *
 * @return void
 */
function check_gtin( $post_id ) {

    $gtin = get_post_meta( $post_id, 'gtin', true );

    if( ! empty( $gtin ) ) {
        echo "gtin13:{$gtin}";
    } else {
        echo 'identifier_exits:false';
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.