[wp-hackers] getting post_id at plugin load time

Owen Winkler ringmaster at midnightcircus.com
Tue Apr 5 13:33:34 GMT 2005


Brett Taylor wrote:
> Any other ideas?

I have a plugin (Redirectify) that gets the Post ID when you would need 
it.  Redirectify redirects visitors to a different URL when they visit 
the single (comments-enabled) page with a "redirect" meta key in it.  In 
order to do this, the plugin must know the Post ID before content is 
sent so that the header can be set, otherwise that "Headers already 
written" error is thrown.

If you hook 'template_redirect' you can get the Post ID from $wp_query 
directly, like so:

add_action('template_redirect', 'foo_fn')
function foo_fn($nothing)
{
	global $wp_query;
	if(is_single() /* || is_page() */) {
		setcookie('lastpostid', $wp_query->post->ID);
	}
}

Outside the Loop, I don't think $post is reliable.

Try it.

Owen




More information about the wp-hackers mailing list