How to add stylesheets only to pages with specific shortcode?

2 questions so 2 answers 🙂

Why is the current functions.php not working and adding styles to all
pages? I’m not sure if it’s the global call or the if statement…

It doesn’t work because of the order in which these functions are called. Your shortcode callback is called during rendering post content (most probably the_content function call).

Both wp_enqueue_scripts and wp_head are called much earlier: wp_head somewhere in your themes header.php file and wp_enqueue_scripts during wp_head call.

What’s the best way for me to add the stylesheets to the header of
only the pages that the above shortcode is used on, assuming I will
not know the page ids, etc?

I don’t think there is such “best” way. It’s not a good idea at all. Browsers cache CSS files. So if you have the same CSS on all pages, browser will get it only once. If there are many CSS files for different pages, browser will have to get all of them. So I wouldn’t do it at all, and include these CSS styles in global css file.

Although if you have to include it only on pages that use this shortcode, then (2 solutions, the choice which is better is yours; I think 2nd one is nicer)…

  1. You can add these styles as inline styles. Just be careful to not include them many times. So output them with your shortcode and assure they will be printed only once.
  2. Since posts are already selected, when wp_head/wp_enqueue_scripts is called, you can add some function to this hook, loop through selected posts, check if they’re containing your shortcode and enqueue your CSS if it’s needed. (Of course it won’t be very efficient).

Leave a Comment