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?

2 Answers
2

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…

Leave a Reply

Your email address will not be published. Required fields are marked *