Earliest hook to reliably get $post/$posts

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).

Leave a Comment