Conditionally enqueue scripts and stylesheets on specific pages

There are many use-cases where scripts and stylesheets only need to be loaded on certain pages. One such example would be to only load the JavaScript and CSS stylesheets for Contact Form 7 (a lightweight contact form plugin) on the contact page.

This article will demonstrate how to conditionally load the JS and CSS for CF7, but the concept could be adapted to apply to other plugins.

Preventing/dequeuing the script and styles

NB: For the rest of this article I’ll refer to scripts and styles collectively as assets.

The first thing we need to do is stop the default action of the assets being loaded on all pages. A generic way of achieving this would be to find the assets in the $wp_styles and $wp_scripts variable. However, CF7 provides a filter that can be accessed, for which we can just return false, thus not enqueuing anything:

 * Do NOT enqueue CF7 scripts and styles
add_filter('wpcf7_load_js', '__return_false');
add_filter('wpcf7_load_css', '__return_false');

Now the assets will not load on any pages. Our next task is to specify the pages we’d like to load them on.

Conditionally loading assets

For this particular scenario the assets only need to be loaded on the contact page. WordPress has a suitable function to achieve this, is_page(). This function takes the page id, name or an array of the page ids and names. Contact Form 7 states that the functions to load the assets back in need to be called before the wp_head() hook, therefore we’ll call them in get_header(), which is fired just before:

 * Action: Load Contact Form 7 assets into get_header
add_action('get_header', function() {
    // Load assets only on contact pages.
    if (is_page(['contact', 'contact-us'])) {
        if (function_exists('wpcf7_enqueue_scripts')) wpcf7_enqueue_scripts();
        if (function_exists('wpcf7_enqueue_styles')) wpcf7_enqueue_styles();

As controlled by the outer if statement, these assets are only being called when the page slug is either ‘contact’ or ‘contact-us’. To extend this to enqueue the assets on other pages simply include the pages in the is_page() arguments, or modify the expression to include further conditionals. For example, assume the sidebar for the blog pages had a CF7 form widget, the control statement could be modified to check if the sidebar is active:

if (is_page(['contact', 'contact-us']) || is_active_sidebar('blog-sidebar'))

Wrapping it up

There are many ways this code could be modified to meet specific requirements, just add it to your theme’s functions.php file (or a functionality plugin) and modify as necessary. The examples in this article are specific to Contact Form 7, for a more generic approach to enqueuing and dequeueing JavaScript and stylesheets refer to WordPress’s wp_enqueue_scripts() documentation, or get in touch with our seasoned WordPress developers.