How to Enqueue Scripts & Styles Only When Shortcode Exists
If you are working on a custom WordPress theme or integrating any plugin with your custom theme then there can be a chance where you just want to include javascript or CSS files only if a particular shortcode exists in your WordPress website.
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.
Let me show you, the code to enqueue scripts and styles in WordPress only if a shortcode exists. Add this code in your theme’s functions.php file or in your plugin’s main file and pass the shortcode_tag and other parameters.
Remember: Don’t forget to update the path of your scripts and styles and other parameters as per your needs in the below code. If you don’t know the correct way to enqueue CSS and Javascript in WordPress?.. don’t Worry I have the resources for that as well.
- How to Enqueue CSS, Font-Awesome, Google Fonts in WordPress
- How to Enqueue or Include Scripts, JS, Jquery in WordPress
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.