WordPress: How can I pick plugins directory in my javascript file?

I need to access plugins directory in my customer javascript file. I know we have do have functions to retrieve plugins directory path using php function plugins_url().

However, I need this to retrieve in my js file where I have to put some images.

Read More

Any ideas??

PS: My js file is saved as a javascript file and therefore, I can’t use php tags in it

Related posts

Leave a Reply

3 comments

  1. Use <?php echo plugins_url(); ?> where you want to get the url in the js file.

    For example:

    var pluginUrl = '<?php echo plugins_url(); ?>' ;
    
  2. It’s actually quite easy…
    In functions.php

    wp_enqueue_script( ‘main’, get_template_directory_uri() . ‘/js/main.js’, array(‘jquery’), ‘20151215’, true );

    $translation_array = array( ‘templateUrl’ =>get_stylesheet_directory_uri() ); //after wp_enqueue_script

    wp_localize_script( ‘main’, ‘jsVars’, $translation_array );

    then in the js-file:

    var sitepath=jsVars.templateUrl+"/";
    

    Edit: Just in case it’s not understood completely:
    The translation array is created and contains a key value pair
    The array is then injected as jsVars (javascript variable) into the js scripts
    So basically we (mis)use the translation array to inject variables to JS
    with the wp_localize_script command.
    off course instead of the templateUrl you can define all the params you want with PHP to inject their values into any js file you want.
    In this example we inject the template Url into the main js script via jsVars, but it can be any variable into any js script