How do I load jQuery for only one specific page in my WordPress theme?

╄→гoц情女王★ 提交于 2019-12-11 12:15:29

问题


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!


回答1:


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.




回答2:


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>'
}


来源:https://stackoverflow.com/questions/3482521/how-do-i-load-jquery-for-only-one-specific-page-in-my-wordpress-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!