This code is from my page single-publication.php
.
It outputs the relevant custom fields etc (here wrapped in template tags), but the_content()
won’t output the post content. I’ve resorted to using $post->post_content
(which works), but the mystery remains:
<div class="publication-info">
<?php printf("<h2>%s</h2>", get_the_title() ); ?>
<div class="publication-meta publication-credit"><?php the_publication_credit(); ?></div>
<div class="publication-meta publication-date"><?php the_publication_date(); ?></div><br />
<div class="publication-blurb" style="font-family:sans-serif;"><?php echo $post->post_content; // the_content() doesn't work. Why not? ?></div>
</div>
What’s going on here?
EDIT: I was driven to ask this question because I believed – mistakenly, as it turns out – that $post
working and get_the_title()
returning a title were an ironclad sign of being inside the loop. But apparently this is not the case. cf Codex on The Loop (second para) and Codex on get_the_title() (parameter list). Can anyone explain?
2 s
Some post-related data is not available to get_posts by default, such as post content through the_content()
, or the numeric ID. This is resolved by calling an internal function setup_postdata()
, with the $post array as its argument:
<?php
$args = array( 'posts_per_page' => 3 );
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
setup_postdata( $post ); ?>
<h2><a href="https://wordpress.stackexchange.com/questions/28905/<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php endforeach;
wp_reset_postdata();
?>
See Access all post data