jasonbradberry
jasonbradberry

Reputation: 873

Adding path to image in jQuery code in Wordpress

I'm adding a jQuery script to add a full screen image background to a page via Backstretch (https://github.com/srobbin/jquery-backstretch).

The problem I'm having is getting the path to the images correct, as I'm using Wordpress.

This is what I've got so far:

<script>
    jQuery(document).ready(function($){                    
        $(".primary-container").backstretch(
        "/library/images/image.jpg");               
    });
</script>

I have tried using <?php bloginfo('template_directory') ?> at the start of the url but I believe this doesn't work in jQuery. How do I go about using a url that links to the image in this case?

Thanks.

Upvotes: 2

Views: 4329

Answers (1)

Jared Cobb
Jared Cobb

Reputation: 5267

Jason, I believe you're running into a somewhat classic challenge with WordPress and JavaScript assets. You need a PHP variable (or some sort of PHP processing) accessible to your JavaScript, and of course, JavaScript can't parse PHP!

Some of the comments suggest inspecting paths (to simply get your directory as it's been generated) but I'm not a fan of that approach as it assumes your theme path will always be the same. (And this can change if you rename your theme folder, change themes, or simply change your folder structure).

I will typically inject a "helper" script in the <head> of all my themes. It's a very simple JSON object that's name-spaced (to keep the global scope clean).

<script>
// for bootstrapping page level code
var YOURSITENAME = {
    "isFrontPage":<?= (is_front_page() ? 'true' : 'false'); ?>,
    "isPage":<?= (is_page() ? 'true' : 'false'); ?>,
    "postName":'<?= get_post_name(); ?>',
    "templateURI":'<?= get_template_directory_uri(); ?>',
};
</script>

Notice the last item titled "templateURI". In your JavaScript you can now access this value anytime using the namespaced JSON object like so:

var myDirectoryPath = YOURSITENAME.templateURI;

Or in your specific example:

var imagePath = YOURSITENAME.templateURI + "/library/images/image.jpg";

jQuery(document).ready(function($){                    
    $(".primary-container").backstretch(imagePath);               
});

Of course, change YOURSITENAME to some more meaningful namespace for yourself.

Have fun!

Upvotes: 4

Related Questions