What’s the earliest possible action I can hook into where I’ll be able to access the global $post/$posts
variables on both the front and back ends? I’ve tried looking through the Codex reference, Adam Brown’s reference and skimming through the source several times but haven’t had much luck finding a good one.
pre_get_posts
is too early; Using posts_selection
doesn’t work if you want to make a second get_posts() call during the callback; and template_redirect
doesn’t run on the admin side. the_post
might be earlier than template_redirect
for the front end, but it also doesn’t run on the back end. Ideally I’d want something that runs right before get_post()/get_posts()
returns, but I’m not seeing anything like that.
I’ve used the the_posts
filter in the past, but I’d prefer an action because it’s more technically correct.
Right now I’m just hooking in twice; once using template_redirect
for the front end, and again using admin_xml_ns
for the back end. I don’t really like that, though, since the my logic isn’t semantically related to either of those hooks, and it seems like this is a very common need and there should be a hook like “post_get_posts” (ala pre_get_posts
) that works on both sides.
For all admin pages and front end pages except individual post edit screens (
wp-admin/post.php
),'wp'
is the most reliable hook for getting the global values.http://phpxref.ftwr.co.uk/wordpress/nav.html?wp-includes/class-wp.php.source.html#l486
You can see there that it fires immediately after
WP::main()
firesWP::register_globals()
. The problem with using things likepost_results
andget_posts
is that it will run every time you make a query for posts.'wp'
only fires in the functionWP::main()
, which is what WP core uses to run the page’s main request query.For post edit screens, it looks like the first hook you can use reliably would be
'add_meta_boxes'
. You would just need to make sure that you’re on a core page when hooking in, although it does pass the global$post
object as the second argument (the first being the$post_type
of the current post).posts_results
is the filter on the raw query result. see line 2627 inwp-includes/query.php
.