How to add javascript file in WordPress shortcode

WordPress allows us to dynamically change the content of the page or post using short code and their attributes.

We can create a shortcode and allow the users to enter any value as attribute, and then use the dynamic value of that attribute as an output for the page.

WordPress shortcode for functions.php

Add this code to your WordPress functions.php file:

function nabtron_jsshortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'path' => 'default-path.js',
        ), $atts, 'path' );

    return '<script type="text/javascript" src="'.$atts['path'].'"></script>';
}
add_shortcode( 'jsshortcode', 'nabtron_jsshortcode' );

Shortcode to be added in page or post content

In your page or post content, paste this shortcode and change value of the attribute path

[jsshortcode path="https://example.com/complete-path.js"]

This will output the javascript include link at the location of javascript short code that we just added.

Please let me know if you have any query or difficulty in implementing it.

Leave a Reply

Your email address will not be published.