将除主页以外的所有页面的脚本出列

时间:2014-12-08 作者:Desi

我正在尝试将一些脚本从我只需要用于主页的插件中删除。对于主页,我使用了一个名为front-page.php 把这个放在上面home 模板:

<?php
/*
Template Name: Home
*/
?>
函数正在删除脚本,但正在删除所有页面上的脚本。我希望只为主页加载脚本。我试过了if ( !is_page_template(\'home.php\') ) { 还有if ( !is_front_page() ) { 但它们都产生了与第一次相同的结果。

function wpcyclone_dequeue_script() {
   wp_dequeue_script( \'jquery-cycle2\' );
   wp_dequeue_script( \'jquery-cycle2-swipe\' );
   wp_dequeue_script( \'cyclone-client\' );
}
if ( !is_page(\'Home\') ) {
    add_action( \'wp_print_scripts\', \'wpcyclone_dequeue_script\', 100 );
}
我哪里出错了?

2 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

Just a few notes on your code

  • You should dequeue and deregister a script to remove it completely from the $wp_scripts global

  • You should not be using wp_print_scripts, this is the wrong hook. You should be using wp_enqueue_scripts

  • Don\'t wrap your action in a conditional. Your conditional tag might either be set to early or to late and might cause unexpected behavior.

  • There is a dedicated conditional tag for the frontpage, is_front_page() that you can use to check if your page is the front page

Your code should look something like this

add_action( \'wp_enqueue_scripts\', \'my_deregister_javascript\', PHP_INT_MAX );

function my_deregister_javascript() {
    if ( !is_front_page() ) {
        wp_dequeue_script( \'jquery-cycle2\' );
        wp_deregister_script( \'jquery-cycle2\' );

        wp_dequeue_script( \'jquery-cycle2-swipe\' );
        wp_deregister_script( \'jquery-cycle2-swipe\' );

        wp_dequeue_script( \'cyclone-client\' );
        wp_deregister_script( \'cyclone-client\' );
    }
}
SO网友:Desi

没关系,我通过另一种方式找到了答案:

add_action( \'wp_print_scripts\', \'my_deregister_javascript\', 100 );

function my_deregister_javascript() {
   if ( !is_page(\'Home\') ) {
    wp_deregister_script( \'jquery-cycle2\' );
    wp_deregister_script( \'jquery-cycle2-swipe\' );
    wp_deregister_script( \'cyclone-client\' );
     }
}
仍然好奇为什么之前的方法不起作用。

结束

相关推荐