发布存档页面-正确关闭WP_QUERY循环

时间:2021-05-24 作者:810311

我正在尝试使用本文中显示的循环示例Output yearly archive within a page输出按年份分组的帖子链接

enter image description here

page-archive.php

<?php
/**
 * Template for displaying archive page
 **/

get_header();
?>

    <main id="primary" class="page-archive">


  <h1>Archive</h1>

  <?php 
// https://wordpress.stackexchange.com/questions/144570/output-yearly-archive-within-a-page
$posts = new WP_Query (
  array (
    \'post_type\'=>\'post\', 
    \'post_status\'=>\'publish\', 
    \'posts_per_page\'=>-1
    )
  ); 
 
if ( $posts->have_posts() ) : ?>
 

 
    <!-- the loop -->
    <?php while ( $posts->have_posts() ) : $posts->the_post(); 
          $year = get_the_time(\'Y\');

           if ($posts->current_post === 0) 

           printf( \'<h3>%s</h3>\', $year ); 
           
          elseif ($last_year !== $year)
           printf( \'<h3>%s</h3>\', $year );
      

    ?>       
          <div>
                
                <a href="<?php the_permalink() ?>"><?php the_title() ?></a>
                <div><?php the_time( \'j F Y\' ) ?></div>
            </div>


    <?php
            if ( ( $posts->current_post + 1 ) === $posts->post_count ) echo \'</li>\'; // Always close the <li> at the end of the loop
        $last_year = $year;

        endwhile;

    ?>


    <?php endif ?>
    <!-- end of the loop -->
 

    </main><!-- #main -->

<?php
get_sidebar();
get_footer();

Question:

在以下内容中if statement 如果条件为真,作者会回应li

if ( ( $posts->current_post + 1 ) === $posts->post_count )
            echo \'</li>\'; // Always close the <li> at the end of the loop
     $last_year = $year;
然而,既然我不需要输出任何东西,只想在没有更多帖子时关闭循环,那么正确的方法是什么?

1 个回复
SO网友:810311

删除以下代码行

if ( ( $posts->current_post + 1 ) === $posts->post_count )
        echo \'</li>\';
只留下以下部分

 <?php
        
    $last_year = $year;

    endwhile;

?>