All Articles Kinsa Creative

Only Enqueue Styles and Scripts for a WordPress Shortcode If That Shortcode Has Been Used in the Post Being Viewed

Only loading the styles and scripts that the shortcode depends on when the shortcode is in use will keep the scripts from being loaded for every other post, keeping the page weight down.

Referencing the WordPress Developer Resources.

Where my-shortcode is the name of the shortcode and my_script.js, referenced as my_script which is in the js directory of the theme is the script to enqueue.

function my_shortcode_scripts() {
    global $post;
    if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my-shortcode') ) {
        wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', '', '', false );
add_action( 'wp_enqueue_scripts', 'my_shortcode_scripts');


Email us at