Support

Account

Home Forums Front-end Issues Passing the_field() as a JS variable

Solving

Passing the_field() as a JS variable

  • Hi,

    I’m trying to pass a the_field() output (an image URL) to a JS file as variable to add a custom marker to a Google Maps map.

    Is that possible in any way?

    Thanks

  • Going to need some more information. Are you just trying to put the variable in a script tag on the page or something else. But yes, it’s possible, just need more information on what you have in mind because depending on what you’re doing there may be different ways to do it.

  • I’m using an external .js file to load all my JS code, and there is where I load the map. The way to add an custom marker is:

    var image = ‘imageurl’;
    var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image
    });
    }

    So I was wondering if there’s a way to take the url from the_field(‘marker_image’). Maybe as a variable or something, not sure.

    Thanks for the help!

  • I would use wp_localize_script https://codex.wordpress.org/Function_Reference/wp_localize_script

    You could also just echo the values into a script tag on the page, but localizing the script would be the preferred method for an external script.

    
    <script>
      // echo a php value into a js variable on page
      var map_url = '<?php  the_field('map_url'); ?>';
    </script>
    
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.