Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Auto-enqueue all CSS files from the theme directory for frontend
- */
- function auto_enqueue_theme_styles() {
- // Only proceed if we're on the frontend
- if (!is_admin()) {
- // Get the theme directory path
- $theme_dir = get_template_directory();
- // Function to recursively get all CSS files
- function get_all_css_files($dir) {
- $css_files = array();
- // Get all files in the current directory
- $files = glob($dir . '/**/*.css');
- foreach ($files as $file) {
- // Skip admin-specific CSS files
- if (strpos($file, 'admin') === false) {
- $css_files[] = $file;
- }
- }
- return $css_files;
- }
- // Get all CSS files from theme directory
- $css_files = get_all_css_files($theme_dir);
- // Sort files to ensure consistent loading order
- sort($css_files);
- // Make sure style.css loads first if it exists
- $main_style = get_template_directory() . '/style.css';
- if (file_exists($main_style)) {
- wp_enqueue_style(
- 'theme-main-style',
- get_template_directory_uri() . '/style.css',
- array(),
- filemtime($main_style),
- 'all'
- );
- }
- // Enqueue all other CSS files
- foreach ($css_files as $css_file) {
- // Get the file path relative to the theme directory
- $relative_path = str_replace($theme_dir . '/', '', $css_file);
- // Create a unique handle for each file
- $handle = 'theme-' . str_replace(['/', '.css'], ['-', ''], $relative_path);
- // Get the file's URI
- $css_uri = get_template_directory_uri() . '/' . $relative_path;
- // Skip style.css as it's already enqueued
- if ($relative_path !== 'style.css') {
- wp_enqueue_style(
- $handle,
- $css_uri,
- array('theme-main-style'), // Make all styles dependent on main style.css
- filemtime($css_file),
- 'all'
- );
- }
- }
- }
- }
- add_action('wp_enqueue_scripts', 'auto_enqueue_theme_styles');
- /**
- * Optional: Add preload for critical CSS files
- */
- function add_critical_css_preload() {
- if (!is_admin()) {
- // Add preload tags for important CSS files
- $critical_files = array(
- 'style.css',
- 'assets/css/critical.css'
- );
- foreach ($critical_files as $file) {
- $file_path = get_template_directory() . '/' . $file;
- if (file_exists($file_path)) {
- $file_url = get_template_directory_uri() . '/' . $file;
- echo '<link rel="preload" href="' . esc_url($file_url) . '" as="style">';
- }
- }
- }
- }
- add_action('wp_head', 'add_critical_css_preload', 1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement