Wondering how I can add a stylesheet to wp_head section via shortcode, since shortcodes are parsed after wp_head, I've hearing about output buffering but I Am not sure.

Any idea?

3 Answers 3


here is a handy function i use a lot which is based on the_posts hook

function check_for_shortcode($posts) {
    if ( empty($posts) )
        return $posts;

    $flag = false;

    foreach ($posts as $post) {
        if ( stripos($post->post_content, '[YOUR_SHORTCODE_HERE') )
            $flag = true;

    if ($flag){
        //add scripts and styles here eg:
    return $posts;
add_action('the_posts', 'check_for_shortcode');

change YOUR_SHORTCODE_HERE to your shortcode tag and add your styles where it says

//add scripts and styles here


If you add your stylesheet via wp_head, your styles will be applied just fine.

This works for one of my plugins:

add_action( 'wp_head', 'my_custom_css' );

function my_custom_css(){
    echo apply_filters( 'my_custom_css', '<link rel="stylesheet" href="' . plugins_url( 'css/my-custom-css.css', __FILE__ ) . '" type="text/css" />' );

To have a user override your CSS file and use the styles in their stylesheet, have them place the following into their functions.php file.:

add_filter( 'my_custom_css', '__return_false' );

Doing it this way gives you and the user the benefit to cache the file instead of systematically trying to determine if the shortcode is on the page or not. Plus, you'll give control back to the user by letting them override your CSS in favor of their own.


I use the YepNope script loader to load all the external CSS/JS. Within your plugin, check to see if the shortcode has been run, then either set a global var or a class variable (depending on implementation. I recommend using classes). If that variable is true, then add the script loader to wp_footer.

When the site loads, the script loader will automatically grab your CSS/JS and append them to the header of your site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.