Support

Account

Home Forums Front-end Issues How to use the_field() data inside javascript

Solved

How to use the_field() data inside javascript

  • BACKGROUND
    I am developing a recipe website. Google’s preferred Schema markup is to put it in the HEAD using the following structure:

    <script type="application/ld+json">
         {
          "@context": "http://schema.org/",
          "@type": "Recipe",
          "name": "Strawberry-Mango Mesclun Recipe",
          "image": "http://images.media-allrecipes.com/userphotos/600x600/1116471.jpg",
          "author": {
          "@type": "Person",
          "name": "scoopnana"
         },

    REFERENCE
    https://developers.google.com/search/docs/data-types/recipes#examples

    I’ve created the necessary ACF fields and can get them to echo into the HEAD. But, not being well-versed in JS, I haven’t been able to figure out to then get the information inside the <script> where it belongs. In the HEAD I can turn the_field data into a JS variable like this:

        <script type="application/ld+json">
         var recipeName = '<?php the_field('recipe_name'); ?>';
         </script>
    

    But then I can not figure out how to make recipeName show as the property of the "name": inside the <script>

    What am I missing?

  • Hi Trishah,

    Try doing an echo for any php that you want to appear inside a JS:

    
    <script type="application/ld+json">
         var recipeName = '<?php echo the_field('recipe_name'); ?>';
    </script>
    

    or

    
    <script type="application/ld+json">
         var recipeName = '<?php echo get_field('recipe_name'); ?>';
    </script>
    
  • Thank you for your reply.

    I went back and looked at all the code again and I can’t figure out what I was doing wrong before. When I did as your suggested (which I thought I had already tried) then this time it did work! Weird. In case any one else wants to know, this is what worked:

    <script type="application/ld+json">
         {
          "@context": "http://schema.org/",
          "@type": "Recipe",
          "name": "<?php the_field('recipe_name'); ?>",
          "image": "http://images.media-allrecipes.com/userphotos/600x600/1116471.jpg",
          "author": {
          "@type": "Person",
          "name": "scoopnana"
         }
         }
    </script>

    Thank you. Please mark as resolved.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.