Site Overlay

How to enqueue scripts or styles only if a shortcode exists on a page

In general, it is a best practice to only enqueue a script or style on your website, only where you need it.

Specifically, this helps with performance.

And in any case, why would you need yourSocialLogin.css file in every page of your website anyway, right?

So, let’s say you are adding a custom shortcode that relies on custom scripts and styles to be rendered correctly on your site’s frontend.

To enqueue the scripts and styles only on pages where the shortcode is implemented, you need to first check if the current is a page and if the page’s content has the shortcode.

For this, WordPress provides the functions is_page() and has_shortcode.

Also, remember to invoke the global $post variable so you can access the post object.

Something like this:

function check_if_page_has_my_shortcode(){

global $post; // To access the current post object.

  if(is_page() && has_shortcode($post->post_content, 'my_shortcode_tag')){
  
       return true; // The shortcode is in the page's content.
  
  } else {
  
       return false;
  
  }

}

That’s it!

Until next time.

Leave a Reply

Your email address will not be published. Required fields are marked *