These codes below automatically output css, based on Template Hierarchy.
When you are watching index.php, these codes output the index.css link, like < link rel=”stylesheet” href=”https://ounziw.com/wp-content/themes/THEMENAME/css/index.css” />. When you are watching, category.php, these codes output the category.css.
add_action('wp_head','page_template_css') ; function page_template_css() { global $template; $dir = '/css'; // css directory. relative path from your theme. $pos = strrpos($template, "/"); $template = substr($template, $pos); $filename = str_replace('php', 'css', $template); $fullfilename = get_stylesheet_directory() . $dir . $filename; if (file_exists($fullfilename)) { print '<link rel="stylesheet" type="text/css" href="' . get_stylesheet_directory_uri() . $dir . $filename . '" />'; print "n"; } }
You don’t have to use lots of if-clause, and still get different css files for different template php files. I hope these codes will help those who customize themes.