【问题标题】:Wrong post title displaying from wordpress loop从 wordpress 循环显示错误的帖子标题
【发布时间】:2015-02-16 15:09:35
【问题描述】:

我正在构建自己的主题。我为我的博客设置了一个页面(带有我制作的模板),我想只显示我的一些帖子。它使用以下循环:

<?php
   query_posts('post_type=post');
   if (have_posts()) {
      while (have_posts()) {
?>

<div class="blog_post">
   <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
   <div class="entry_date"><?php the_time('F jS, Y') ?></div>
   <?php
      the_post();
      the_content();
   ?>
</div>

<?php
      }
   }
?>

我的帖子的标题分别是“First Post、Second Post、Third Post 和Fourth Post”。当帖子显示在博客页面上时,它们以正确的顺序显示,但帖子的标题不正确。第一篇文章的标题是:“第二篇文章”。第二篇文章的标题是:“第三篇文章”,依此类推,直到最后一篇(最近的)文章标题为:“博客”(页面标题)。被他们搞砸的标题怎么了?

我的尝试: 在我来这里之前,我已经研究了很多。我尝试使用 get_the_title() 代替,但这导致没有显示任何标题。我也尝试过使用 the_title_attribute() 无济于事。我也明白我不应该在这个循环中使用 query_posts,但我不确定在这种特殊情况下使用哪种方法来获取帖子的正确方法。我读过的大部分信息都不清楚,似乎并没有解决问题。

非常感谢任何帮助。

【问题讨论】:

    标签: wordpress-theming wordpress


    【解决方案1】:

    试试这样的:未测试

    <?php
    global $post;
    $args = array();
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :
      setup_postdata($post); ?>
        YOUR HTML HERE
    <?php endforeach; 
    wp_reset_postdata(); ?>
    

    【讨论】:

      【解决方案2】:

      好吧,没关系!我刚刚发现问题出在哪里。我将“the_post()”移到了 while 循环之后,所以现在它看起来像这样:

      <?php
              query_posts('post_type=post');
              if (have_posts()) {
                  while (have_posts()) {
                      the_post();
                      ?>
                      <div class="blog_post">
                          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                          <div class="entry_date"><?php the_time('F jS, Y') ?></div>
                          <?php
                          the_content();
                          ?>
                      </div>
                      <?php
                  }
              }
              ?>
      

      我在阅读 wordpress codex 中的 the_post() 时发现了这个解决方案。原来这个函数正在为该行中的下一篇文章设置信息,所以它不应该与当前文章的 html 输出混在一起。

      关于我是否应该使用“query_posts()”仍然是我不确定并愿意接受任何建议的事情。但是当前形式的循环正在运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2021-03-26
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多