Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

If I call the following function (on a page template, e.g. page-home.php) before the loop, nothing is returned. If I call it during or after the loop, the expected values are returned. Is there a way to access these meta fields before the loop runs?

function home_content() {
    global $post;
    $headline = get_post_meta($post->ID, 'top-headline', true);
    $body = get_post_meta($post->ID, 'top-body', true);
    $return = '<h4>' . $headline . '</h4>';
    $return .= '<p>' . $body . '</p>';
    echo $return;
}
share|improve this question
    
$post doesn't contain anything until the loop runs. You can however check(i think) $posts prior to when the loop runs. –  t31os Aug 12 '11 at 17:06
add comment

1 Answer 1

up vote 3 down vote accepted

You can get it by calling global $wp_query and assigning post->ID to a variable.

<?php

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

?>
share|improve this answer
    
Thanks, that worked perfectly! –  tnorthcutt Aug 12 '11 at 18:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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