Paulund

Add Scripts To Shortcode Only When Used

Since version 2.5 WordPress introduced a new way of developers to provide dynamic content for the content author of the website with the use of Shortcodes.

What Is A Shortcode?

A shortcode allows the user to run a PHP function at any point you want in the content. A default shortcode you get with WordPress is the gallery shortcode, to add a gallery to your website all you have to do is add [ gallery ] to the content area of your website. The name inside the square brackets is the name of the shortcode that you want to run at this position of the content. WordPress will then search for shortcodes on the the_content filter and using the function do_shortcode() will run the functions at this point of the content, the return of these functions will then be output into the rest of the content area. Shortcodes allows you to send extra parameters to the function by using attributes.

[shortcode_example attribute1="stuff" attribute2="things"/]

In the shortcode function the developer can now look up these attributes and use these values to change the output. You can also add content into the shortcode along with the attributes.


[shortcode_example attribute1="stuff" attribute2="things"]Shortcode Content Can Go Here[/shortcode_example]

This is great for the author as they now have full control of any functions that can help add dynamic controls to the site.

Styles And Scripts In Shortcodes

As shortcodes are used to add more dynamic content to the site it can be used to add Google maps or another third party to your application. If you want to add these third parties to your website then this would normally be done with Javascript. When you use Javascript in your WordPress site you would normally have to use the action wp_enqueue_scripts.

add_action( 'wp_enqueue_scripts', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Problem With Scripts And Shortcodes

The problem we get with shortcodes and queuing script files is that whenever we register the shortcode we need to register the Javascript at the same time. This means that WordPress will load the shortcode and the Javascript with the page even when the Shortcode isn't being used. add_shortcode( 'google_map', 'add_google_map'); function add_google_map( $atts, $content ) { }

add_action( 'wp_enqueue_scripts', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Therefore if we have a Google Maps shortcode we will be including the Google Maps Javascript file on every page of our WordPress site even if the shortcode isn't being used. There is no need to include the Javascript on a page where the Google map isn't being displayed we are just adding more weight and slowing down the page. So we need to find a way of only loading the Javascripts when the shortcode is being used, how can we solve this problem? We could add the wp_enqueue_script() inside the shortcode function like this.

add_shortcode( 'google_map', 'add_google_map');
function add_google_map( $atts, $content )
{
    wp_enqueue_script(...);
}

But this won't work, it's too late, WordPress will not run be able to queue up the scripts. The solution would be to add the Javascript in the footer of the application using wp_footer. Adding the script in the footer event allows us to set a global variable at the point of running the shortcode code, then in the wp_footer action we can do a check for this global variable and if it's set then we add the Javascript into the footer of the page.


add_shortcode( 'google_map', 'add_google_map');
function add_google_map( $atts, $content )
{

}

add_action( 'wp_footer', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Shortcode OOP Class

The easiest way of doing this is by using a class to add the shortcode to the application. The following class will demo how you can make sure you only add Javascript when the shortcode is being used. We start off by creating a class variable of $addScript and set this to false, this is the variable we are going to use to see if the shortcode is ran. Next we add a constructor to the class, the purpose of the constructor is to define the actions and register the shortcode. The important thing to notice is in the shortcode function we start off by changing the value of the variable to true, so that in the footer action the shortcode function would of already ran, so we can check if this class variable is true. If the $addScript variable is still false, then we know the shortcode didn't run and we don't need to add the Javascript.


$shortcode = new Shortcode_Class();
class Shortcode_Class
{
    /**
     * If you should add the script or not
     *
     * @var bool
     */
    private $addScript = false;

    public function __construct()
    {
        add_shortcode('test_shortcode', array($this, 'shortcode_content'));

        // wp_enqueue_scripts
        // If you use the below the CSS and JS file will be added on everypage
        // add_action( 'wp_enqueue_scripts', array($this, 'add_shortcode_scripts'));

        // Add styles and scripts to the page
        add_action('wp_footer', array($this, 'add_shortcode_scripts'));
    }

    public function shortcode_content( $attr, $content )
    {
        $this->addScript = true;
        ?>
        <h1>Shortcode Content Being Displayed</h1>
        <?php
    }

    public function add_shortcode_scripts()
    {
        if(!$this->addScript)
        {
            return false;
        }

        wp_enqueue_script('shortcode-js', get_stylesheet_directory_uri() . '/js/shortcode.js', false);
    }
}