Enqueue Script Relative to PHP File

The Customizer Library is package of helper classes and functions that developers can use in their themes. Since I don’t necessarily know what the folder will be named or where it will be located in the theme- any javascript needs to be loaded relative to the file that enqueues it.

To do that, I use this trick to determine the URL for the script relative to the file:

$file = dirname( __FILE__ );

// Get the URL and path to wp-content
$content_url = untrailingslashit( dirname( dirname( get_stylesheet_directory_uri() ) ) );
$content_dir = untrailingslashit( WP_CONTENT_DIR );

// Fix path on Windows servers
$file = wp_normalize_path( $file );
$content_dir = wp_normalize_path( $content_dir );

$uri = str_replace( $content_dir, $content_url, $file );

* This snippet was updated 02/11/16 based on code from Duluxe Blog Tips, which fixes issues with relative loading in Windows server environments.

Of course, if you do know the path to the JS file, it’s recommended you use:

wp_enqueue_script( 'example-script', get_template_directory_uri() . '/path/example.js' );

And this is just for themes. If you’re doing this in a plugin, you can use:

wp_enqueue_script( 'example-script', plugins_url( 'path/example.js' , dirname(__FILE__) ) );

Hope this helps!

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

1 Response

  1. i tried this. But, it only work on some servers.
    For example, while building on a local host this doesnt work ;(
    also, on godaddy (some people still host there hehe )

    In any case, thanks for trying

Leave a Reply to Sagive Cancel reply