Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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() fires WP::register_globals(). The problem with using things like post_results and get_posts is that it will run every time you make a query for posts. 'wp' only fires in the function WP::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).

share|improve this answer
    
Thanks John, it looks like that's gonna work :) –  Ian Dunn Jul 13 '11 at 21:29

posts_results is the filter on the raw query result. see line 2627 in wp-includes/query.php.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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