Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Load Scripts if Post has Short Code

Posted on July 15, 2011 by Pippin in Advanced, Intermediate, Short Codes, Tutorials, Working with jQuery, Writing Plugins 16 Comments
Home» Tutorials » Advanced » Load Scripts if Post has Short Code
Tweet
Love It - 0

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.

Tweet Follow @pippinsplugins
Scripts. styles, short codes, shortcodes

16 comments on “Load Scripts if Post has Short Code”

  1. Alex says:
    July 16, 2011 at 6:29 am

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

    Reply
  2. Dalton says:
    July 16, 2011 at 5:50 pm

    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?

    Reply
  3. Dalton says:
    July 16, 2011 at 6:11 pm

    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 )

    Reply
  4. pippin says:
    July 16, 2011 at 8:26 pm

    @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.

    Reply
  5. Stephanie says:
    July 21, 2011 at 8:47 am

    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).

    Reply
  6. Chris Aprea says:
    July 26, 2011 at 4:32 am

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

    Reply
  7. Samiullah Khan says:
    July 26, 2011 at 10:09 pm

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

    Reply
  8. Dipak says:
    July 29, 2011 at 7:53 am

    Thanks pippin
    very useful post for me !!

    Reply
  9. Franklin says:
    June 1, 2012 at 5:06 am

    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.

    Reply
    • Pippin says:
      June 1, 2012 at 9:06 am

      Yep, that should work just fine.

  10. Franklin says:
    June 1, 2012 at 5:09 am

    Forgot to mention that you can find a tutorial here

    http://wp.tutsplus.com/articles/quick-tip-improving-shortcodes-with-the-has_shortcode-function/

    Reply
    • Pippin says:
      June 1, 2012 at 9:06 am

      lol, just so happens that I wrote that tutorial ;)

  11. Franklin says:
    June 1, 2012 at 9:15 am

    Wow….nice somehow I had totally missed that.
    Thanks :)

    Reply
  12. Josh Kurz (@JoshKurz) says:
    February 14, 2013 at 4:05 am

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

    Reply
  13. orionrush says:
    March 3, 2013 at 5:11 am

    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

    Reply
    • Pippin says:
      March 4, 2013 at 2:28 pm

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

Leave a Reply Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Never Remove the Default the_content Filters in Themes
  • User Friendly Short Codes Plugin Example
  • WP Utility Short Codes Plugin
  • Shortcodes Pro Premium Plugin Review
  • Add a Short Code to Your Plugin

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes

Latest Tutorials

  • Storing Session Data in WordPress without $_SESSION (19)

    The term Session in web development refers to...

  • Test Your Plugins with RTL (1)

    Right-To-Left languages are those that...

  • Submitting Your First Pull Request to a WordPress Plugin on Github (5)

    Github is an extremely popular tool for managing WordPress plugins, and one...

Enter your email to receive automated updates when new posts are published

WP Core Contributions

  • [24316]

View the ticket on Trac.

WP Codex Contributions

  • Function: shortcode exists
  • Function: has shortcode
  • Function: shortcode exists
  • Function: shortcode exists
  • Function: has shortcode

View all 41 changes in the Codex.

Latest Tweets

  • Could not fetch Twitter RSS feed.

Topics

attachments featured hook meta box campaign monitor wp_enqueue_script Rémi Corson shortcodes Tom McFarlin get_user_meta contextual help register_setting add_shortcode image plugin forms do_action short codes mail chimp Related posts login authors attachment post types apply_filters comments recent posts short code bbpress taxonomies custom post type Ajax images gallery Stripe jquery taxonomy widgets users add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2013 Pippin's Plugins