views:

27

answers:

2

I'm fiddling with a WordPress theme. I'm aware I can use wp_enqueue_script in my header.php to load WordPress's supplied jQuery library.

I was just going to use wp_enqueue_script in my header, but it seems inefficient when I only want to use it on a particular Page (just on one single page with a particular page_id.)

Given that, what's the best way of including jQuery only on one particular Page?

Presumably I can't do page_id detection in header.php, because that won't be in The Loop, right? But I'm guessing I'm missing some fairly obvious method -- I'm fairly new to theme development...

Thanks!

A: 

here is an article about dynamic body ids
http://perishablepress.com/press/2009/05/26/dynamic-body-class-id-php-wordpress/
after you get your page name you can add a conditional statement in your template index.php that says something like this in your page header or before the closing body tag:

// $page_name would be the page name you extracted with a function from the post
if($page_name === 'about'){
    echo '<script type="text/javascript" src="jquery.js"></script>'
}
pferdefleisch
+1  A: 

Yes you can, is_page doesn't need to be called in The Loop, since it doesn't change when The Loop runs. So is_page(42) will only return TRUE if you're on the page with id 42. It also works with the page title or name (slug), which might be more future-proof if you ever replace delete this page and replace it with a new one with the same slug.

Jan Fabry
Ahh, thanks! I had a feeling I was missing something obvious. I ended up with is_page('contact'), as if I use the slug instead of the ID then I'll actually remember what I was doing when I look at the code again in three months' time!
Matt Gibson
I heard they have a good remedy for these memory problems in PHP. It appears you can put an explaination of what you intended to do between slashes and stars, and others will be able to understand you months, even years later! :-)
Jan Fabry
@Jan Yes, but what's more readable, `if (is_page(42)) /* If it's the contact page */`, or `if (is_page('contact'))`? I'm a good commenter, but if I can make the code stand on its own, so much the better...
Matt Gibson