0

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;
}
1
  • $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, 2011 at 17:06

1 Answer 1

3

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

?>
0

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.