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 register_more_stylesheetswpse39130_register_more_stylesheets() {
wp_register_style( 'stylesheet_name', get_stylesheet_directory_uri() . '/stylesheet.css' );
}
add_action( 'init', 'wpse39130_register_more_stylesheets' );
function add_my_stylesheetwpse39130_conditionally_enqueue_my_stylesheet() {
if (// is_page('products-services')only )enqueue //on usingproduct-services page slug
wp_enqueue_styleif ( 'stylesheet_name'is_page( );'products-services' ) //) no{
brackets needed for one line and no else
}
add_actionwp_enqueue_style( 'init', 'register_more_stylesheets''stylesheet_name' ); // should I
use wp_print_styles hook instead?}
}
add_action( 'wp_enqueue_scripts', 'add_my_stylesheet''wpse39130_conditionally_enqueue_my_stylesheet' );
When I remove the conditional part of it, the stylesheet is successfully enqueued so I know that works.