Michael Gunner

Michael Gunner

© 2013 Michael Gunner. All rights reserved.

Use WordPress get_template_directory function in external JavaScript

Here’s a useful snippet. If you develop for WordPress, you’ve probably found you either have to hard code URLs in your external JavaScript…or put the JavaScript in line. Neither of these is ideal because the first won’t work when the theme is installed on a different URL, and the second will make your header look bloated and possibly slow your site down. It’s just not good practice to have JavaScript in line.

But there is a way, and it’s very simple. First, you need to declare a JavaScript variable in your Head.

<script type="text/javascript">
var templateDir = "<?php bloginfo('template_directory') ?>";
</script>

Make sure this is before your external JavaScript. Now, where you need to echo that function in your script, you simply echo the variable instead. E.g:

$.get(templateDir + "/inc/ajax.php", { Variable1: Variable1, Variable2: Variable2});

If you ever find yourself needing to use other WordPress theme functions in your Javascript, there’s no reason you couldn’t use the same principle with other functions.

1 Comment

  1. Guilherme Almeida

    I’ve been struggling to solve this problem of relative paths in a external .js file for a week, and couldn’t find a simpler solution (I’m a designer, not a developer). Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>