How To: Add Inline Scripts and Conditionally Enqueue Scripts & Styles in WordPress

Sometimes when making a theme or plugin, you want to conditionally enqueue a script or style so that it does not load on pages where it is not used. This process is generally pretty straight forward, just add your enqueue functions inside of conditional statements like this:


add_action('wp_enqueue_scripts', 'add_script_function');
function add_script_function() {
  if(condition one === true) {
    wp_enqueue_script('script1', 'location/script1.js');
  } else {
    wp_enqueue_script('script2', 'location/script2.js');
  }
}

While updating Eazy Flickity Slider, I found myself needing to conditionally enqueue an inline script that would cause a function to fire on a DOM element. The solution I came up with was to add the inline script as a PHP function, then to add that function in the footer as part of the enqueue, after the files it is dependent on have loaded.

3 Comments

Rob Scott gravatar icon Rob Scott

It is probably a good idea to use something like that if you are not going to optimize the site ‘by hand’, meaning individually optimized for the specific plugins and themes being used.

Reply

Leave a Reply

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