3

It would be a right way to enqueue the scripts using foreach loop only for jquery, jquery-ui-widget, jquery-UI-accordion, jquery-ui-slider, jquery-ui-tabs, jquery-ui-datepicker, Jquery-ui-dialog and Jquery-ui-button because I have to write it many times so

I have make it like this:

 $jquery_ui = array(
    'jquery',
    'jquery-ui-core',
    'jquery-ui-widget',
    'jquery-ui-accordion',
    'jquery-ui-slider',
    'jquery-ui-tabs',
    'jquery-ui-datepicker',
    'jquery-ui-dialog',
    'jquery-ui-button',
 );

 // Framework JS
foreach ($jquery_ui as $ui) {
    wp_enqueue_script($ui);
}

So I just want to know this laziness is a right way or not:)

1
  • 2
    Yes. But you don't need to enqueue jquery and -core manually as WordPress has the dependencies set up properly. Just enqueue those you want. And nothing wrong with a foreach here
    – kero
    Commented Jul 27, 2017 at 15:41

2 Answers 2

1

Yes you can. But to make sure the script has not already been registered or enqueued, use wp_script_is() as follows:

foreach( $jquery_ui as $ui ) {
    if( !wp_script_is( $ui ) ) {
        wp_enqueue_script( $ui );
    }
}

This will prevent conflicts due to another instance of the script being already enqueued.

0

It is actually even easier than that. wp_enqueue_script() accepts an array of script handles, so you can simply do this:

$jquery_ui = array(
    'jquery',
    'jquery-ui-core',
    'jquery-ui-widget',
    'jquery-ui-accordion',
    'jquery-ui-slider',
    'jquery-ui-tabs',
    'jquery-ui-datepicker',
    'jquery-ui-dialog',
    'jquery-ui-button',
 );

wp_enqueue_script( $jquery_ui );

There is no need to check whether the script has already been registered using wp_script_is(), as wp_enqueue_script() handles this for you and will never enqueue the same script (handle) twice. By calling wp_script_is() as well, you are performing an identical check twice unnecessarily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.