3

I am using wp-store-locator plugin and I want to add plugin directory path to my JS.

html = "<li data-store-id='" + id + "'><div><p>" + storeImg + "<strong>" + store + "</strong><span class='wpsl-street'>" + address + "</span>" + address2 + city + " " + state + " " + zip + "</p>" + moreInfo + "<span><a href='plugin-urlpath/store-listings.php' class='more-details'>More details</a></span></div></li>";

return html;

How can I do that ? Plugin path is at the end of html.

EDITED:

This what I have done :

wp_enqueue_script( 'wpsl-gmap', ( "//maps.google.com/maps/api/js?sensor=false&libraries=places&language=" . $this->settings['api_language'] ), false, '', true ); 
wp_localize_script('wpsl-gmap', 'wpsl-gmap', array('pluginsUrl' => plugins_url(,__FILE__)));

Then Added this line to wpsl-gmap.js

var href = wpsl-gmap.pluginsUrl + '/path/to/resource';
html = "<li data-store-id='" + id + "'><div><p>" + storeImg + "<strong>" + store + "</strong><span class='wpsl-street'>" + address + "</span>" + address2 + city + " " + state + " " + zip + "</p>" + moreInfo + "<span><a href='" + href + "' class='more-details'>More details</a></span></div></li>";

It is giving no errors.But it is also not showing me the store location as well.

NOTE It was showing properly before doing this.

1 Answer 1

10

Use wp_localize_script() to pass any kind of data to your loaded scripts, in this case we need plugins_url():

wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js');
wp_localize_script('my-script', 'myScript', array(
    'pluginsUrl' => plugins_url(),
));

Now you will have access to myScript.pluginsUrl in your script file:

var href = myScript.pluginsUrl + '/path/to/resource';
1
  • 3
    First, the second argument of wp_localize_script is the object name or variable name that will be accessible in JS and this name should contain only valid characters and the dash - is not, so try wp_localize_script('wpsl-gmap', 'wpslGmap' .. instead. Second, I dont know if this is a typo, but first argument must be provided in plugins_url() to pass the second argument, so fix your code to plugins_url('', __FILE__).
    – Ahmad M
    Commented Oct 16, 2014 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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