[wp-hackers] How to make $post->ID global

Charles K. Clarkson cclarkson at htcomp.net
Fri May 11 02:54:37 UTC 2012

On 5/10/2012 8:28 PM, David Law wrote:

> Trying to use code like this within the include file
> global $post;
> $stmeta2011headeror = get_post_meta($post->ID, 'st_meta_2011header_or', true);
> But $post->ID isn't generating the ID, replacing $post->ID with a posts ID
 > (1 for example) results in the code working as expected when viewing post
> 1, so the only problem is obtaining the current posts ID (which should be
>  easy) on an included PHP file.
> Using this code within header.php
> $stmeta2011headeror = get_post_meta($post->ID, 'st_meta_2011header_or', true);
> echo $stmeta2011headeror;
> Outputs the posts meta field entry.
> I've tried
> $post->ID
> $wp_query->post->ID
> get_the_ID()
> Confused :-)

header.php runs after $post has been defined.

Your include file runs before $post is defined.

The trick to make your include file function is to add it or its code with
an action that takes place after $post has been defined.

If header.php is okay, use add_action( 'wp_head', 'your_function' ) where
your function runs the code you want to add to the theme header.php file.


Charles Clarkson
Free Market Advocate
Mobile Home Investor

I'm not really a smart person. I just play one on the Internet.

Stephenville, TX
+1 (254) 434-2733

More information about the wp-hackers mailing list