【问题标题】:Wordpress: Add to wp_head() from pageWordpress:从页面添加到 wp_head()
【发布时间】:2011-10-14 15:51:43
【问题描述】:

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

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

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    如果你看这里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。当然,如果您在正确的页面上,也许您想以其他方式进行测试,但我认为这说明了这个想法。

    【讨论】:

      【解决方案2】:

      怎么用?

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

      【讨论】:

      • 我在最初的问题 (is_page_template()) 中介绍了类似的方法。
      【解决方案3】:

      我相信你可以通过functions.php 做到这一点。如果你从那里做它会更整洁。我建议,除非那个 js 文件真的很大,否则最好将它包含在任何地方,并使用 wp-minify 将所有 js 文件组合成一个。

      【讨论】:

        猜你喜欢
        • 2014-03-02
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多