我有一个由 WordPress 驱动的网站,我的 header 包含在文件 header.php
中。在另一个页面上,我想运行一个脚本,该脚本仅在该页面上需要。
脚本应该加载到该页面的页眉中,但仅限于该页面。将脚本包含在 header.php
中会在所有其他页面上加载该脚本。
如何最好地将脚本包含在 page-pageslug.php
模板中?
最佳答案
在 wp_head();
上方的 header.php
中,使用
if ( is_page( 'page-slug' ) ) {
wp_register_script( 'your-script', get_bloginfo('template_url') . '/js/your-script.js' );
wp_enqueue_script( 'your-script' );
}
page-slug
就是您想要定位的页面的 slug。
<强> wp_enqueue_script()
:
Description
The safe and recommended method of adding JavaScript to a WordPress generated page is by using wp_enqueue_script(). This function includes the script if it hasn't already been included, and safely handles dependencies.
关于javascript - 在页面模板上加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258946/