1

I'm trying to place a small code in my template header.php file. I want to get a custom field value.

I'm trying to call custom fields from current page outside of loop, btw.

I have no problem doing this when I need to get custom field values from posts, but I can't seem to do this for pages.

Here is my code:

global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'teaser-text', true);

I'm not sure what I'm doing wrong. I tried changing $wp_query->post->ID; to this $wp_query->page->ID; to no success.

Any help is appreciated, thank you!

3 Answers 3

2

try using

get_metadata('post', $postid, 'teaser-text, true);

these two actually same. should not make any difference. earlier i gave wrong arguments. var_dump() will show you what it is actually getting. please make sure, the ID is correct, 'teaser-text' exists. You can also try using some other meta name (for testing purpose only).

9
  • This seems to be the correct way to do it. I still cannot get it to work though. I'm even hardcoding the page id into the arguments.
    – RCorrie
    Jun 18, 2012 at 14:51
  • sorry to hear but what problem you are getting? i've checked this and working at my end. try var_dump(). does 'teaser-text' exist for the page? Jun 18, 2012 at 14:55
  • The value is just not printing. And yes the custom key is filled into the page. Is there a setting where I have to enable custom fields for pages? Maybe..?
    – RCorrie
    Jun 18, 2012 at 15:05
  • my above code will just return. for printing you need to echo what you receive like echo get_metadata('page', $postid, 'teaser-text, true); Jun 18, 2012 at 15:10
  • 1
    Solved it, I messed around a bit more with get_post_meta() and it does in fact work with pages. Thanks for your help!
    – RCorrie
    Jun 18, 2012 at 15:29
1

This is untested, but try:

if ( is_page() ){
    $page_id = get_queried_object_id();
    $meta = get_post_meta( $post_id, 'teaser-text',true)
}
0
0

You'll have to either start the loop, then rewind it:

$wp_query->the_post(); // Now $post is the first post (page) in the loop
echo get_post_meta( $post->ID, 'teaser-text', true );`
$wp_query->rewind; // This rewinds the query so the loop functions normally

Or just pull the ID from the first post in the query:

echo get_post_meta( $wp_query->posts[0]->ID, 'teaser-text', true );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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