I'm working on a custom theme framework for educational purposes.

I basically have a header.php in a child theme that i want to make smarter. I'd like to only include a stylesheet if the file exist. Getting 404 errors is not cool or efficient.

Are there native php or wordpress functions to check if a wordpress file exist.

Basically... I want to output

<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/css/<?php echo get_stylesheet() ?>.css" type="text/css" media="screen" />

Only If the stylesheet with the same name as the folder containing the child theme exist.

Any ideas would be awesome :-)

  • style.css is the first thing that WordPress looks for in a theme directory – Bainternet Feb 10 '11 at 21:36
  • 1
    Without a style.css you don't have a theme so if that's the only file you want to check for then you have no need... – MikeSchinkel Feb 10 '11 at 21:58
  • Thanks mike...That's a good point. I"m kind just trying extend my child themes, to always look for a foldername.css file automatically. And keep a consistent style.css file among all the child themes that i'm creating. – Wok Feb 25 '11 at 1:52

There's a lot of ways you could go with this. I might enqueue the style in your theme's functions.php dependent on a file_exists() check.

$your_css_file_path = "/path/to/file";
if ( file_exists($your_css_file_path) ) {
    wp_register_style('your_theme_stylesheet', $your_css_file_path);
    wp_enqueue_style( 'your_theme_stylesheet');

Here's the relavent core source.

  • 1
    Just be aware that file_exists uses a path relative to the current directory(that of the executing file), and enqueues use a path relative to the WordPress installation, the path may not point to the same place for both cases. – t31os Feb 11 '11 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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