Load plugin scripts only on pages that need them

Posted on

To disable messy plugin from loading on every page of your site (just on the pages that need it)…

First find the handle — Open the php for the script you want to turn off and look for where it adds itself via enqueue_script

wp_enqueue_script(‘wpng-calendar‘, get_bloginfo(‘wpurl’) . ‘/wp-content/plugins/wpng-calendar/js/functions.js’, array(‘date-js’), ’0.85′);

(if the plugin doesn’t use enqueue_script then you may be out of luck)

Then add this to your functions.php file:

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 ); 
function my_deregister_javascript() {
if ( !is_page('Events') ) {
wp_deregister_script( 'wpng-calendar' );
wp_deregister_script( 'date-js' );
wp_deregister_script( 'thickbox-js' );
wp_deregister_script( 'jquery-js' );
wp_deregister_script( 'wiky-js' );
}
}

If you need to show the plugin on multiple pages, change the if line to this:

if ( !is_page(array(2,'events','about-us')) ) {
Posted in Wordpress Tips, Tricks and Reusable Bits of Code.