• I’ve got a line in my theme’s functions.php which initializes a set of classes, which contain all of my theme’s functions, filters, hooks, etc. It basically sets up the site.

    I’ve recently begun to investigate site performance issues, and I noticed that my classes are being initialized multiple times per page view. To my understanding, functions.php should only be loading once.

    After some debugging, I realized that the general protection against this is apparently in wp-blog-header, which contains the conditional check of $wp_did_header. But for some reason, functions.php was still running multiple times.

    So I traced back all the way to the beginning, index.php, which sets the whole chain in motion. Actually, I went back even further, to my htaccess file, which contains the standard WP rewrite rules:

    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    So the first rule says “if they request index.php, give it to them”, and the second rule says “if what they are requesting is not a file, and it’s not a directory, give them index.php instead”

    The problem I am having, it seems, is in handling 404’s. As far as I can tell, if I have any missing images on my site, a request is made for the file, this second htaccess rule recognizes that it is not a file (since it doesn’t exist) and sends the request to index.php, which in turn starts the chain that loads functions.php unnecessarily, essentially loading my entire site again for no reason.

    I feel like this can’t be the way that WordPress is supposed to operate, and yet, I’m at a loss, since I thought this was the standard setup for htaccess.

    My current plan for solving this is to add a conditional check in functions.php before initializing my classes, which checks the REQUEST_URI for image file extensions, though I have not fully explored the possible ramifications of doing this; at first glance, the site appears to function fine, and my database query times are greatly reduced.

    So my question is: is it normal for requests for files that result in 404 to initialize WordPress again, loading files like functions.php multiple times per page load? From htaccess up the chain to functions.php getting loaded, the files are all core. And yet I have not found anyone else with a similar issue…

  • The topic ‘functions.php Running Multiple Times Per Page View’ is closed to new replies.