While making changes to my WordPress theme, I noticed that the error_log file in my theme folder contained dozens of PHP Fatal error lines:
... [01-Jun-2011 14:25:15] PHP Fatal error: Call to undefined function get_header() in /home/accountname/public_html/ardamis.com/wp-content/themes/ars/index.php on line 7 [01-Jun-2011 20:58:23] PHP Fatal error: Call to undefined function get_header() in /home/accountname/public_html/ardamis.com/wp-content/themes/ars/index.php on line 7 ...
The first seven lines of my theme’s index.php file:
<?php ini_set('display_errors', 0); ?> <?php /** * @package WordPress * @subpackage Ars_Theme */ get_header(); ?>
I realized that the error was being generated each time that my theme’s index.php file was called directly, and that the error was caused by the theme’s inability to locate the WordPress get_header function (which is completely normal). Thankfully, the descriptive error wasn’t being output to the browser, but was only being logged to the error_log file, due to the inclusion of the ini_set(‘display_errors’, 0); line. I had learned this the hard way a few months ago when I found that calling the theme’s index.php file directly would generate an error message, output to the browser, that would reveal my hosting account username as part of the absolute path to the file throwing the error.
I decided the best way to handle this would be to check to see if the file could find the get_header function, and if it could not, simply redirect the visitor to the site’s home page. The code I used to do this:
<?php ini_set('display_errors', 0); ?> <?php /** * @package WordPress * @subpackage Ars_Theme */ if (function_exists('get_header')) { get_header(); }else{ /* Redirect browser */ header("Location: http://" . $_SERVER['HTTP_HOST'] . ""); /* Make sure that code below does not get executed when we redirect. */ exit; }; ?>
So there you have it. No more fatal errors due to get_header when loading the WordPress theme’s index.php file directly. And if something else in the file should throw an error, ini_set(‘display_errors’, 0); means it still won’t be sent to the browser.