Calling custom fields for pages (not posts)

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.

Read More

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!

Related posts

Leave a Reply

3 comments

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

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