Solve the problem of WordPress hooks firing more than once on a single page load with some simple conditionals to ensure your hooks aren’t getting load on other requests like for favicons & assets.
Fire Hooks Once Per Page Load
I’ve ran into this problem numerous times where I find a WordPress hooks like template_redirect
, init
, wp
, etc. are getting fired more than once on a single page load. After some digging and Googling, it appears it’s caused by other requests during a page load like the site’s favicon or assets.
Here’s the solution I came up using WordPress conditionals to verify the request is for an actual page vs. resources or images:
<?php
add_action( 'template_redirect', 'fire_once' );
function fire_once() {
// Make sure the request is for a user-facing page
if (
! is_singular() &&
! is_page() &&
! is_single() &&
! is_archive() &&
! is_home() &&
! is_front_page()
) {
return false;
}
// Otherwise do your thing
}
What about only firing on the frontend vs. backend?
Just like the example above, we’re going to ensure the requests are for actual pages & then check if the requested page is in the admin dashboard using the is_admin()
conditional:
<?php
add_action( 'template_redirect', 'fire_once' );
function fire_once() {
// Make sure the request is for a user-facing admin dashboard page
if (
! is_admin() ||
! is_singular() &&
! is_page() &&
! is_single() &&
! is_archive() &&
! is_home() &&
! is_front_page()
) {
return false;
}
// Otherwise do your thing
}
Do you know a better way?
I would love to hear it! Seems like everyone has their own way of approaching this issue so would always open to other better ideas to accomplish this. Comment below to share your thoughts.
All comments posted on 'Ensure WordPress Hooks Fire Once' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.
You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.
Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.