Enqueue All Stylesheets Found In a Theme Folder

Is there a built-in Wordpress function that will allow you to enqueue all stylesheets for a particular theme?

I have a directory structure that looks like:

-my-custom-theme
    -css
        -header.css
        -footer.css
    -functions.php

I want to load all CSS files found in the my-custom-theme/css folder

Topic wp-enqueue-script css themes Wordpress

Category Web


As Jacob mentioned, if this is a theme you are developing, you could name the CSS files in alphabetical order of the order you want to load them. Then you could use a function to read the list of files, sort them in alphabetical order, then loop through each one and enqueing them.

But, if all the CSS files need to be loaded, and it's your theme, why not just put them into one combined CSS files. You could use media queries to limit the CSS processed, although systems are fast enough now that the time required to load a big CSS file might be minimal enough not to worry about a giant CSS file.

And, if it's your theme, one css-enquee loop should take care of loading all the needed CSS files in the order that is desired.

But one giant CSS file seems to be less trouble.


You could enqueue_script both files.

// Add custom css
function my_CSS() {
    wp_register_script( 'header', get_template_directory_uri() . '/my-custom-theme/css/header.css', array(), 1, true );
    wp_enqueue_script( 'header' );

    wp_register_script( 'footer', get_template_directory_uri() . '/my-custom-theme/css/footer.css', array(), 1, true );
    wp_enqueue_script( 'footer' );  

}
add_action('wp_enqueue_scripts', 'my_CSS');

No. You need to specify each stylesheet that you want your theme to enqueue. Doing it automatically would almost certainly cause issues, since the order that CSS is loaded is very important to how styles are applied. If the correct loading order for your theme's stylesheets just happened to be alphabetical order that might not be a problem, but it wouldn't be the case for most themes.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.