I’m trying to dequeue some scripts from a plugin that I only need for the home page. For the home page, I’m using a file called front-page.php
with this on top to make it a home
template:
<?php
/*
Template Name: Home
*/
?>
The function is removing the scripts, but it’s removing them on all pages. I want the scripts to only load for the home page. I’ve tried if ( !is_page_template('home.php') ) {
and also if ( !is_front_page() ) {
but they both produced the same outcome as the first.
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 );
}
Where have I gone wrong?
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' );
}
}