Before I get started, I want to acknowledge that there are some really good articles that are targeted at how to conditionally enqueue scripts based on page/post content.

  • WordPress Plugin Development – How To Include CSS and JavaScript Conditionally And Only When Needed By The Posts
  • How to load JavaScript like a WordPress Master

These are great, but they’re much more advanced than what I want to do.

I feel like the answer is using the built-in is_page() function (codex), but when I try to use it the site breaks, or just doesn’t work.

I think I’m just executing the conditional logic in the wrong spot.

Here’s what I’ve tried to add to my functions.php:

function wpse39130_register_more_stylesheets() {
    wp_register_style( 'stylesheet_name', get_stylesheet_directory_uri() . '/stylesheet.css' );
}
add_action( 'init', 'wpse39130_register_more_stylesheets' );

function wpse39130_conditionally_enqueue_my_stylesheet() {
    // only enqueue on product-services page slug
    if ( is_page( 'products-services' ) ) {
        wp_enqueue_style( 'stylesheet_name' );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse39130_conditionally_enqueue_my_stylesheet' );

When I remove the conditional part of it, the stylesheet is successfully enqueued so I know that works.

3 s
3

I copy pasted your code into my dev environment, changed nothing but the page name, and it works just fine. Are you sure that it’s not being enqueued and you just have it pointed wrong or that the page is not named incorrectly or something?

Leave a Reply

Your email address will not be published. Required fields are marked *