问题描述

此代码来自我的页面 single-publication.php

它输出相关的自定义字段等 (这里包含在模板标签中),但 the_content()不会输出帖子内容。我已经诉诸于使用 $post->post_content(它的作品),但是这个奥秘依然存在:

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

这里发生了什么?

编辑:我被问到这个问题,因为我相信 – 错误地说,事实证明,$post 的工作和 get_the_title()返回一个标题是循环中的一个铁皮标志。但显然不是这样。 cf Codex on The Loop(第二段) 和 Codex on get_the_title()(参数表) 。有人可以解释吗

最佳解决方案

一些 post-related 数据默认不可用于 get_posts,例如通过 the_content()发布的内容或数字 ID 。这通过调用内部函数 setup_postdata()解决,$ post 数组作为其参数:

<?php
$args = array( 'posts_per_page' => 3 );
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
  setup_postdata( $post ); ?>
    <h2><a href="<?php%20the_permalink();%20?>"><?php the_title(); ?></a></h2>
    <?php the_content(); ?>
<?php endforeach;
wp_reset_postdata();
?>

请参阅访问所有帖子数据

次佳解决方案

你的 HTML 很有可能不被包含在循环中。确保您的代码如下所示:

if(have_posts()): while(have_posts()): the_post(); ?>

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

<?php endwhile; endif;

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。