How to Enqueue Scripts & Styles Only When Shortcode Exists

If you are working on a WordPress theme or plugin then there can be a chance where you only want to include javascript or CSS files only if a particular shortcode exists.

To check shortcode existence WordPress gives a function shortcode_exists($shortcode_tag).

By using this function, you can check if a shortcode exists or not and then you can enqueue any scripts and styles there.

Add this code in your theme’s functions.php file or in your plugin’s main file and pass the shortcode name as shortcode_tag.

This code snippet will enqueue your scripts & style only if a shortcode exists. however, if you want to enqueue your files only if that shortcode is getting used on the page?.

Then I have written a separate article about enqueueing scripts & styles only if the shortcode getting used on the page.

Remember: Don’t forget to update the path of your scripts and styles and other parameters as per your needs in the below code.

function enqueuing_scripts_styles(){

	if(shortcode_exists('my-shortcode-name')) {
	
	// Enqueue Scripts and Styles Here

    wp_enqueue_style( 'custom-css', get_template_directory_uri().'/css/custom.css');
    wp_enqueue_script( 'custom-js',  get_template_directory_uri().'/js/custom-js.js');
	
	}

}

add_action( 'wp_enqueue_scripts', 'enqueuing_scripts' );

I hope this article helps you to understand, how to enqueue scripts and style only when a particular shortcode exists.

Owner of diveinwp.com, solely responsible for creating helpful, informative content about WordPress, a fulltime WordPress developer with 8+ years of hands-on experience in WordPress design and development.