I want to simplify the scripts and the stylesheet loading in my wordpress plugin. I have this code style now, but I want to implement a best solution, this to encache the function readbility. Is there any way to enqueque the scripts and styles with a foreach? I was thinking to implement a check to verify if the script or style is already enqueued and then if not, load it.
Here is the code.
// plugin class method
public function init() : void
{
if( !wp_script_is( 'popper-js' , 'enqueued' ) ){
wp_enqueue_script( 'popper' , PLUGIN_DIR.'/js/popper.min.js', ['jquery'] );
}
if( !wp_script_is( 'bootstrap-js' , 'enqueued' ) ){
wp_enqueue_script( 'bootstrap' , PLUGIN_DIR.'/js/bootstrap.min.js', ['jquery'] );
}
if( !wp_style_is( 'bootstrap-css' , 'enqueued' ) ){
wp_enqueue_style( 'bootstrap' , PLUGIN_DIR.'/css/bootstrap.min.css' );
}
if( !wp_script_is( 'parallax-js' , 'enqueued' ) ){
wp_enqueue_script( 'parallax' , PLUGIN_DIR.'/js/universal-parallax.min.js' );
}
if( !wp_style_is( 'parallax-css' , 'enqueued' ) ){
wp_enqueue_style( 'parallax-css' , PLUGIN_DIR.'/css/universal-parallax.min.css' );
}
if( !wp_script_is( 'swiper-js' , 'enqueued' ) ){
wp_enqueue_script( 'swiper' , PLUGIN_DIR.'/js/swiper.min.js' );
}
if( !wp_style_is( 'swiper-css' , 'enqueued' ) ){
wp_enqueue_style( 'swiper-css' , PLUGIN_DIR.'/css/swiper.min.css' );
}
}
I want to avoid to call the wp_style_is
or wp_script_is
and the related wp_enqueue_
functions. my pseudo code solution is this, but any suggestion will be appreciated:
public function init() : void
{
// check if the file has the -js or -css name
//$resources = [ 'swiper-css', 'swiper-js' ];
foreach( $resouces as $res ){
if( !wp_script_is( , 'enqueued' ) || !wp_style_is( 'swiper-css' , 'enqueued' ) ){
wp_enqueue_style( $res.'-css' , PLUGIN_DIR.'/css/'.$res.'.min.css' );
wp_enqueue_script( $res.'-js' , PLUGIN_DIR.'/js/'.$res.'.min.js' );
}
}
}