Display scripts and styles when a shortcode exists in WordPress

Using shortcode to display conditional data is a common approach in WordPress. When the plugin contains many script and style files, we need to include them only when a shortcode presents in a post or page.

Use has_shortcode()

This is straight forward approach. has_shortcode( string $content, string $tag ) determines whether the passed content contains the specified shortcode.

If the current page is a post and its content contains our defined shortcode, color_shades, the script will be enqueued with wp_enqueue_script function.

function color_shortcode_scripts() {
    global $post;
    if( get_post_type($post) == 'post' && has_shortcode( $post->post_content, 'color_shades') ) {
        wp_enqueue_script('color-script', plugin_dir_url(__FILE__).'color-script.js'
    );
    }
}
add_action( 'wp_enqueue_scripts', 'color_shortcode_scripts');

Use class

We use a variable to store boolean value to determine whether shortcode exists. When color_shades_render (shortcode handler) is called, the value is set to true. Then we use it as condition to print styles and scripts.

class ColorShadesShortcode {
     //allow script when the shortcode exists in a post 
    static $hasShortcode;

    static function init() {
        add_shortcode('color_shades', array(__CLASS__, 'color_shades_render'));
        add_action('init', array(__CLASS__, 'register_scripts'));
        add_action('wp_footer', array(__CLASS__, 'print_scripts'));
        add_action('wp_head', array(__CLASS__, 'print_styles'));
    }
    static function color_shades_render($atts) {
        self::$hasShortcode = true;

        extract(shortcode_atts(array(
            'color_name' => 'orange',            
        ), $atts));

        $output = "show list of orange's shades here";
        return $output;
    }
    //register scripts and styles
    static function register_scripts() {
        wp_register_script('script-name', plugins_url('script-name.js', __FILE__), array('jquery'), '1.0', true);
        wp_register_style( 'style-name', plugins_url( 'style-name.css', __FILE__ ), true, '', 'all' );
    }

    //print scripts if shortcode_name exists
    static function print_scripts() {
        if (!self::$hasShortcode)
            return;
        wp_print_scripts('script-name');
    }

    //print styles if shortcode_name exists
    static function print_styles() {
        if (!self::$hasShortcode)
            return;
        wp_print_styles( 'style-name' );
    }
}
ColorShadesShortcode::init();

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close