Restricting a Plugin to Only Load its CSS and JS on Selected Pages?

Styles and scripts are always set up by the functions wp_enqueue_script() and wp_enqueue_style(), which have to be tied to a particular action hook in order to function. I took a peek inside Contact Form 7, and it looks like it’s using action tags of wpcf7_enqueue_scripts and wpcf7_enqueue_styles to add them to the wp_print_scripts and wp_print_styles hooks.

So, what you need to do is un-hook the scripts and styles from every page but your contact page. The wp_head action fires before the script and styles actions, so you’ll need to add something like this to your theme’s functions.php file:

function remove_wpcf7_extras() {
    remove_action('wp_print_scripts', 'wpcf7_enqueue_scripts');
    remove_action('wp_print_styles', 'wpcf7_enqueue_styles');
}

if( ! is_page('contact me') ) {
    add_action('wp_head', 'remove_wpcf7_extras');
}

The is_page() function will return true when you’re on the contact page (assuming the name is “contact me”) … you can also use the page slug and page ID for the filter. On all other pages, the if() conditional will add the script/style removal function to the wp_head action, which fires just before the wp_print_scripts and wp_print_styles actions.

This should remove the extra code from your pages, and you won’t have to deactivate the plug-in or edit any core files. The functions and code I’ve listed above also won’t cause your theme to break if you remove Contact Form 7 in the future, either … so no need to worry about future upgrade compatibility.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)