Welcome friend. Don't forget to check out Moderno, my latest premium WordPress theme!

Close Notification

How To Load Scripts In WordPress Only If A Post Has A Shortcode

As usual it is best practice to load your styles and scripts for your WordPress Themes only when needed, to keep the site loading quickly and to avoid any JS errors. In order to do this, there are tons of built-in conditionals to check if a post is using a specific template, if it’s the homepage, search page, admin page…etc, so you can load your styles and scripts only on the pages that require them, however,  there isn’t any built-in way to test if a post has a shortcode in the content.

Many people simply load all their javascript and CSS for their shortcodes into their header by using the wp_enqueue function, but this is not really the best method. When you are developing a site you should always strive for speed/performance.

Today I got a really handy WordPress function from my buddy at PippinsPlugins (the best site on the web for WordPress plugins at plugin tutorials) which allows you to check if a certain shortcode exits on a post and if it does load your scripts.

Shortcode Check Function

Simply copy and edit (change YOUR_SHORTCODE to the name of the shortcode you want to check for) the function below to test your posts for the existence of a shortcode and load your scripts/styles when needed!

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');
"If you liked this post please share it!"