Home>

We are currently working on the WordPress template to do the same thing as the title.
As a specific image, I would like to make the following page template.

Category: hogehoge

FY2019
xx month xx article title
xx month xx article title

FY2018
xx month xx article title
xx month xx article title

FY2017
xx month xx article title
xx month xx article title

On the other hand, the code currently created is as follows.

(page-hogehoge-no-matome.php)

<? php
query_posts ('category_name = hogehoge&posts_per_page = -1');
if (have_posts ()): while (have_posts ()): the_post ();
$post_year = get_the_date ('Y');
?>
    <? php if ($post_year == '2020'):?>
        <span>FY2020</span>
              "><p><? php the_time ('Ymd');?><p><? php the_title ();?></p >
    <? php elseif ($post_year == '2019'):?>
        <span>2019</span>
              "><p><? php the_time ('Ymd');?><p><? php the_title ();?></p >
    <? php elseif ($post_year == '2018'):?>
        <span>2018</span>
              "><p><? php the_time ('Ymd');?><p><? php the_title ();?></p >
    <? php endif;?>
<? php endwhile;endif;?>
<? php wp_reset_query ();?>

The above code is natural, but it will be as follows.

FY2019
xx month xx article title

FY2019
xx month xx article title

FY2018
xx month xx article title

FY2018
xx month xx article title

I only want to display the year once, but if there are any good methods, I would be grateful if you could teach me.

  • Answer # 1

    Based on another question from 8-0_nyan5, I modified and implemented as follows.
    Thank you for teaching!

        'advertisement',             'posts_per_page' =>-1,             'order' =>'DESC'         );         $the_query = new WP_Query ($args);         if ($the_query->have_posts ()):             $post_year = false;             while ($the_query->have_posts ()): $the_query->the_post ();                 if ($post_year! = get_post_time ('Y')) {                     echo ''. get_post_time ('Y'). 'Year article heading ';                 };?>                      ">

                

  • Answer # 2

    Basically, the current post value is compared with the value of the previous post, and the year is output if they differ. I think the flow is good.
    I haven't done error checking, but if I divert existing code, isn't it?

    
        
            
            FY
        
          ">

         Code

Related articles