Wordpress:从页面添加到wp_head()

时间:2011-10-13 16:13:18

标签: wordpress

在Wordpress中,我有一个页面模板,它使用特定的JS文件和CSS文件,而网站的其他部分则不使用。在这个特定的模板页面上,有没有办法在调用wp_head之前将这些项添加到头部?

我意识到我可以在条件中使用is_page_template(),但我的头文件已失控。

3 个答案:

答案 0 :(得分:4)

如果你看这里http://codex.wordpress.org/Plugin_API/Action_Reference,你可以看到在 wp_head 之前调用的钩子是 get_header

所以你需要做的是:添加一个在该钩子上调用的动作,测试你是否在你想要的页面上,以及你是否添加了脚本和css

这会发生在一个插件中(不是像header.php或functions.php这样的主题文件中),它看起来像这样:

// call the function that adds your current script 
add_action('get_header', 'add_that_script');
function add_that_script()
{
    if (is_page(SOME_PAGE_IDENTIFIER)) // this is the page you need; check http://codex.wordpress.org/Function_Reference/is_page on how to use this function; you can provide as a parameter the id, title, name or an array..
    {
        wp_register_script( 'mycustomscript', 'http://www.example.com/script.css'); // register your script 
        wp_enqueue_script( 'mycustomscript' ); // enqueue it to be added in the head section

        wp_register_style( 'mycustomstyle', 'http://www.example.com/example.css'); // register your css 
        wp_enqueue_style( 'mycustomstyle' ); // enqueue it to be added in the head section
    }
}

您只需要替换页面的ID以及js文件和css的URL。当然,如果你在正确的页面上,也许你想尝试其他方式,但我认为这表明了这个想法。

答案 1 :(得分:0)

如何使用?

if(is_page('Your Page Name')): 
// do something for me
endif; 

答案 2 :(得分:-1)

我相信你可以从functions.php做到这一点。如果你从那里做的话它更整洁。我建议,除非js文件非常大,否则你最好把它包含在各处,并使用wp-minify将所有js文件组合成一个。