0

I need to dynamic the image path to my theme file within a javascript file. How would I go about this?

address.forEach(function(address){
   var markerGeoCoder;

   markerImage = {url: window.mr_variant == undefined ? 'img/mapmarker.png' : '../img/mapmarker.png', size: new google.maps.Size(50,50), scaledSize: new google.maps.Size(50,50)};
   if(/(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)/.test(address) ){
       var latlong = address.split(','),
       marker = new google.maps.Marker({
           position: { lat: 1*latlong[0], lng: 1*latlong[1] },
           map: map,
           icon: markerImage,
           title: markerTitle,
           optimised: false
       });
   }

I already tried this :

address.forEach(function(address){
    var markerGeoCoder;

    markerImage = {url: window.mr_variant == undefined ? '<?php the_field('img/mapmarker.png'); ?>' : '../img/mapmarker.png', size: new google.maps.Size(50,50), scaledSize: new google.maps.Size(50,50)};
    if(/(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)/.test(address) ){
        var latlong = address.split(','),
        marker = new google.maps.Marker({
            position: { lat: 1*latlong[0], lng: 1*latlong[1] },
            map: map,
            icon: markerImage,
            title: markerTitle,
            optimised: false
        });
    }

But it's not working.

  • Is your script in a <script></script> tag in a template, or in a .js file that you're enqueueing? – Jacob Peattie Jul 24 '17 at 7:28
  • r in a .js file – Ananda Mukherjee Jul 27 '17 at 6:31
0

If you're in JS you can't use PHP (<?php ?>), you need to another way to get a PHP variable into JS. The normal way with WordPress is to use wp_localize_script().

wp_localize_script( 'wpse_274344', 'myScriptObject', array(
    'markerImageUrl' => get_theme_file_uri( '/img/mapmarker.png' ),
) );

Add that code after your call to wp_enqueue_script() or wp_register_script(). Replace wpse_274344 with the name you used when enqueuing the script.

This means that WordPress will output a JavaScript object named myScriptObject to the page containing the values that you passed to wp_localize_script().

Then in your script file you can access the markerImageUrl like this:

markerImage = {
    url: window.myScriptObject.markerImageUrl
}

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.