WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a short code that is adding a form to a page. How do I ensure that the CSS for the form is loaded in time with the shortcode?

share|improve this question
up vote 2 down vote accepted

you can check with the_posts hook if your shortcode exists and only enqueue the style if so :

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

    $found = false;

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

    if ($found){
        $url = get_bloginfo( 'template_directory' );
        wp_enqueue_style( 'my_login_Stylesheet',$url.'/my_login_Stylesheet.css' );

    return $posts;
add_action('the_posts', 'check_for_shortcode');
share|improve this answer
So I would store the code in my theme and then call it from the_posts? Would it still be valid if I put the css in my plugin folder? Also, is the_posts called in time? Thanks very much for your help. – Awesome Name Jul 15 '11 at 17:42
just paste this code in your theme's functions.php file, and change the $url.'/my_login_Stylesheet.css to reflect the url to your css file in your plugin folder, and change CHANGE_TO_YOUR_SHORT_CODE to your actual shortcode – Bainternet Jul 15 '11 at 18:33
Wouldn't this only work for the first post found with the short code? It looks like this searches through ALL posts, or does it only search through the post pulled in with the query? – Pippin Jul 15 '11 at 18:50
All posts in current query for all queries – Bainternet Jul 15 '11 at 18:56

You add the css for this form to your theme's style.css. The css is already there no matter if you have a form or not. That's the easiest solution.

share|improve this answer
Is there a ways to do this automatically, via the plugin? – Awesome Name Jul 15 '11 at 16:07
I don't know. You might be able to find a hook or filter to do this. Have a look at the WordPress sourcecode for that. A different (not recommended!) approach could be reading the active theme's style.css and append the new styles to the file. Personally I would go with the elegant solution proposed by Bainternet. – BjornW Jul 30 '11 at 15:55

You can also embed your styles through a tag above the short code HTMl.

share|improve this answer
But I'd advise against this. @Bainternet's solution is much, much better. – Pippin Jul 15 '11 at 16:13

Your Answer


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.