theme path in javascript file

The question:

I need to include the path to my theme file within a javascript file. How would I go about this? I have already tried:

var templateUrl = "<?php get_stylesheet_directory_uri(); ?>";

function LightboxOptions() {
  this.fileLoadingImage = "'"+templateUrl+"/img/loading.gif'";
  this.fileCloseImage = "'"+templateUrl+"/img/close.png'";
  this.resizeDuration = 700;
  this.fadeDuration = 500;
  this.labelImage = "Image";
  this.labelOf = "of";
}

This does not give me the path, but just inserts <?php get_stylesheet_directory_uri(); ?> instead of the actual path. Any ideas? Thanks in advance!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

What you’re looking for is wp_localize_script function.

You use it like this when enqueing script

wp_register_script( 'my-script', 'myscript_url' );
wp_enqueue_script( 'my-script' );
$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
//after wp_enqueue_script
wp_localize_script( 'my-script', 'object_name', $translation_array );

In your style.js, there is going to be:

var templateUrl = object_name.templateUrl;
...

Method 2

These are the following two ways to add theme path in javascript file.

1) You can use wp_localize_script() suggested by wordpress in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

Example :

wp_register_script('custom-js',get_stylesheet_directory_uri().'/js/custom.js',array(),NULL,true);
wp_enqueue_script('custom-js');

$wnm_custom = array( 'stylesheet_directory_uri' => get_stylesheet_directory_uri() );
wp_localize_script( 'custom-js', 'directory_uri', $wnm_custom );

and can use in your js file as following :

alert(directory_uri.stylesheet_directory_uri); 

2) You can create a Javascript snippet that saves the template directory uri in a variable, and use it later as following:
Add this code in header.php file before the js file in which you want to use this path.
Example:

<script type="text/javascript">
var stylesheet_directory_uri = "<?php echo get_stylesheet_directory_uri(); ?>";
</script>

and can use in your js file as following :

alert(stylesheet_directory_uri);

Method 3

You can localize your javascript files, wich gives you the opportunity to generate a javascript array filled with PHP defined values (such as localisation or directories).

If you load your javascript file trough wp_enqueue_script or wp_register_script its easy to set up like follows:

function localize_vars() {
    return array(
        'stylesheet_directory' => get_stylesheet_directory_uri()
    );
}

wp_enqueue_script( 'my_script', plugins_url( 'my_plugin/my_script.js' ), array( 'jquery' ) );
wp_localize_script( 'my_script', 'my_unique_name', localize_vars() );

And in your javascript files, you can call these variables by:

my_unique_name.stylesheet_directory

Method 4

I started using this convenient little method to get the WordPress theme directory and store it as a global JavaScript variable (all from within a javascript file):

function getThemeDir() {
    var scripts = document.getElementsByTagName('script'),
        index = scripts.length - 1,
        myScript = scripts[index];

    return myScript.src.replace(/themes/(.*?)/(.*)/g, 'themes/$1');
}
themeDir = getThemeDir();

This will only work if the following conditions are met:

    1. This snippet is executed via an external JavaScript file – like this:

<script src="/wp-content/themes/themename/assets/app.js"></script>

    2. The js file resides within your site’s theme directory (or subdirectory).

Method 5

This is how I did it.

Place the javascript file and images in theme-folder/assets

And edit the following files.

In functions.php

/* for javascript (only when using child theme) */
wp_enqueue_script('my-script', get_template_directory_uri() . '-child/assets/test.js');
wp_localize_script('my-script', 'myScript', array(
    'theme_directory' => get_template_directory_uri() 
));

In your javascript file

var url = myScript.theme_directory + '-child/assets/';

Method 6

If the javascript file is loaded from the admin dashboard, you can use this javascript function get the root of your WordPress installation.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

Then just contact the path to your theme like below.

var myThemePath = getHomeUrl() + '/wp-content/themes/myTheme';


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment