I am currently building a WordPress theme where I am using jQuery to append and prepend some ornate images to a h4 tag with a class of beechheader in the page template markup.
Before turning the static html files into a WordPress theme, the code below worked great. The code is in a separate file called test.js
The jQuery code appears to be enqueued correctly in the functions file and I have called the test.js code using
<script src="<?php bloginfo('template_directory'); ?>/javascripts/whatever.js"></script>
right before the closing body tag. Here is the code that worked fine statically but now doesnt work
// prepend some images to the headers
$(function() {
$("h4.beechheader")
.prepend('<img src="/images/beechleft.gif" alt="" />')
.append('<img src="/images/beechright.gif" alt="" />');
});
I tried adding
<?php echo get_template_directory_uri(); ?>
before the trailing slash before images as you would in the html file. My research leads me to believe jQuery files may need to be handled a bit differently but I am unsure of the syntax or what to do. Can anyone help?
well first of all, don’t directly inject a script tag like that, use
wp_enqueue_script
to add your javascript file. additional data can then be passed from php to javascript via thewp_localize_script
function.Use
wp_localize_script
to add a Javascript variable to the page.You need to “register” that data to a script that has already loaded. That is why I used
jquery
which is the handle used when WordPress loads its bundled jquery library, but it can be any script handle that loads on the page. See the Codex for details.Search your page source and you should see your data.
You should be able to access the Javascript variable with
my_data.template_directory_uri
. For example,I shouldn’t really be shoving a script into the footer like that (rather than enqueue it) but this is just for testing. Presumably you already have a properly enqueued script that you will use this in.
So you will want something like …