This is a really handy trick that I just learned today. Whenever we can, it is always best to only load styles and scripts for our plugins when they are needed. This tutorial will show you how to load stylesheets and scripts only when a post contains the short code that the styles / scripts target.

So let’s say that we have a short code (provided through our plugin) that displays some content on the site, and this content needs to be styled. We could simply use wp_enqueue_style() to load our stylesheet into the header, but then out CSS file would be loaded on every single page of the site, even though it’s only needed on one or two. We could also simply embed the CSS or JS in STYLE or SCRIPT tags right above or below the short code’s displayed content. But this isn’t optimal either. The best solution is to load the files into the page header if, and only if, the current post or page has the short code inside of its content. And that’s exactly what the following function does:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function check_for_shortcode($posts) {
    if ( empty($posts) )
        return $posts;
 
    // false because we have to search through the posts first
    $found = false;
 
    // search through each post
    foreach ($posts as $post) {
        // check the post content for the short code
        if ( stripos($post->post_content, '[YOUR_SHORTCODE') )
            // we have found a post with the short code
            $found = true;
            // stop the search
            break;
        }
 
    if ($found){
        // $url contains the path to your plugin folder
        $url = plugin_dir_url( __FILE__ );
        wp_enqueue_style( 'my_login_Stylesheet',$url.'plugin_styles.css' );
 
    }
    return $posts;
}
// perform the check when the_posts() function is called
add_action('the_posts', 'check_for_shortcode');

Simply place this function inside of one of your plugin files and you’re good to go. You will need to replace [YOUR_SHORTCODE] with the short code you want to search for, and you will also need to replace plugin_styles.css with your stylesheet name.

You can use this function to load as many styles or scripts as you want.

  1. Alex

    Hello Pippin
    may be
    add_action(‘the_post’, ‘check_for_shortcode’);
    because
    ‘the_posts’ is filter

  2. Dalton

    Thanks, this is super helpful. It works great for me on individual posts and pages, but not on the main index page. Any idea why?

  3. Dalton

    Aha, just found the documentation on the_posts:

    “applied to the list of posts queried from the database after minimal processing for permissions and draft status on single-post pages.”

    So it only works on single-post pages. Is there an equivalent for all posts, or do I just need to change it to:

    if ( $found || !is_single )

  4. pippin

    @Dalton – thanks for pointing that out! Using !is_single() will cause your stylesheet or scripts be to be loaded on every page that is not a single page, more or less negating the point of the function. I’ll play around with it and see if I can make it work on the index pages.

  5. Stephanie

    This is great! So much better than !is_admin wrapping calls for style and scripts.

    Now, to figure out where in other plugins I’ve installed that this can be added… (Contact Form 7, I’m looking especially at you).

  6. Chris Aprea

    Very cool! Bookmarked for later use, no doubt this will come in handy!

  7. Samiullah Khan

    Using WordPress since 2009, but never heard of this thing, thanks pippin

  8. Dipak

    Thanks pippin
    very useful post for me !!

  9. Franklin

    Here is what am using

    note that I’ve placed this in the function.php


    /* ---------------------------------------------------------------------- */
    /* Check the current post for the existence of a short code
    /* ---------------------------------------------------------------------- */

    if ( !function_exists('radium_has_shortcode') ) {

    function radium_has_shortcode($shortcode = '') {

    global $post;
    $post_obj = get_post( $post->ID );
    $found = false;

    if ( !$shortcode )
    return $found;
    if ( stripos( $post_obj->post_content, '[' . $shortcode ) !== false )
    $found = true;

    // return our results
    return $found;

    }
    }

    Then I can call this function from anywhere like so

    if( radium_has_shortcode('gallery') ) {
    //do some stuff here
    }

    This can be used to check any kind of shortcode.

    • Pippin

      Yep, that should work just fine.

    • Joe Buckle

      Franklin,

      I just wanted you to know that this has been very useful to me. Thank you

    • Pippin

      lol, just so happens that I wrote that tutorial 😉

  10. Franklin

    Wow….nice somehow I had totally missed that.
    Thanks 🙂

  11. Josh Kurz (@JoshKurz)

    sweet thanks I just commented on your admin scripts post. Just ignore that. This is the bomb.

  12. orionrush

    This is a very good method and I’ve been using it quite a lot lately. It has one drawback that I’ve run into however: it assumes the shortcode is in the database as part of post content. In some cases users will put your shortcode onto a template using the do_shortcode() function and so the above check wouldn’t see it. I found a thread on stack exchange which discuses variants of Pipin’s technique, and includes an interesting snippet on how to scan the template files for shortcodes: http://wordpress.stackexchange.com/a/75915/13551

    • Pippin

      Thanks for posting. That’s definitely something to take into consideration.

    • Kevin Marshall

      This seems like it would now be the preferred method as it’s built in to WP core. Am I correct in assuming so, or is there a catch where the methodology above is preferred?

    • Pippin

      Yes this is the preferred method now. The only caveat to it is if you wish to support WordPress versions less than 3.6. If so, you may want to create a backup function similar to the one described above.

  13. Kumaresan

    All My post usually uses various plugin based data manipulations (Like visual layout, grouping, plugin css, etc) And now I want to render a post content in my admin page.
    On using following code:

    $post = get_post(123);
    $content = apply_filters(‘the_content’, $post->post_content);
    echo $content;

    It just displaying a formated text content and I can’t see my plugin based alignments, layouts which I usually can see it on normal post.

    So How to get post content for admin panel all formatted along with all plugin based manipulation done?

    • Pippin

      How does your plugin modify the content?

  14. Mickey

    This is great. One question – is there a way to also accomplish this if the shortcode is used in a widget/sidebar, instead of in the content? What about if the shortcode is included manually via PHP? Is there no way to have the actual shortcode trigger the inclusion, instead of checking for the existence of the shortcode from within a prior filter? Thanks!

    • Pippin

      There are ways to do it where you setuo a global variable, define it as true during the short code, then check if it is true later on. It only works for things after the widget though.

Your email address will not be published. Required fields are marked *