How do I load jQuery for only one specific page in my WordPress theme?
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, becaus开发者_如何学运维e 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!
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.
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>'
}
精彩评论