Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

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.

share|improve this answer

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.

share|improve this answer

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;
            break;
        }

    if ($flag){
        //add scripts and styles here eg:
        //wp_enqueue_script
        //wp_enqueue_style
    }
    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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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