Ghazanfar Mir
Ghazanfar Mir

Reputation: 3541

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.

Any ideas??

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

Upvotes: 3

Views: 7437

Answers (4)

daniyal iravani
daniyal iravani

Reputation: 21

To pick the WordPress plugins directory in JavaScript, you usually need to define it dynamically in PHP and then pass it to JavaScript using wp_localize_script.

In your theme or plugin's PHP file:

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', [], '1.0', true);

    wp_localize_script('custom-script', 'wpData', [
        'pluginsUrl' => plugins_url(),
    ]);
});

then in your custom-script.js:

if (typeof wpData !== 'undefined' && wpData.pluginsUrl) { 
var myplugin = wpData.pluginsUrl + '/your plugin folder name';
 }

Upvotes: 0

Ahmed KHABER
Ahmed KHABER

Reputation: 19

I've got the result just by assigning the real plugin url:

let pluginUrl = "../wp-content/plugins/YOUR_PLUGIN_FOLDER_NAME/";

Upvotes: 0

Canelo Digital
Canelo Digital

Reputation: 392

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

Upvotes: 2

Pulkit Goyal
Pulkit Goyal

Reputation: 5674

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

For example:

var pluginUrl = '<?php echo plugins_url(); ?>' ;

Upvotes: 2

Related Questions