0

I'm trying to find anything out there that will list posts under a specific category by date. Here's my example:

Photography (being the category name)

2018

  • Post title shows here
  • Post title shows here
  • Post title shows here

2017

  • Post title shows here
  • post title shows here
  • Post title shows here

I know that this is probably pretty basic wordpress, but all I can really find out there is for all categories, not just one specific one.

1

Even though it is not the most conventional way of doing, I would proceed like this:

Edit : precision I create a new file category.php which is the template for categories, and put this piece of code inside.

$args = array(  'post_type'=>'post',
    'posts_per_page'=> -1,
    'post_status'=>'publish',
    'orderby'=>'post_date',
    'order'=>'DESC'
    );

$query = new WP_Query($args);

if($query->have_posts())
{
    $years = array();
    $postList = '';
    foreach ($query->posts as $post) {

        //if we haven't proceed the year yet
        // we display it
        if(!in_array($year = get_the_date('Y',$post->ID),$years))
        {
            $postList.=sprintf('<h2>%s</h2>',$year);
            $years[] = $year;
        }

        $postList.=sprintf('<h3><a href="%1$s" title="%2$s">%2$s</a></h3>',get_permalink($post->ID),$post->post_title);

    }

    echo $postList;

}else{

    _e('No posts sorry','your-text-domain');

}
| improve this answer | |
  • Now, would I have to specify the category in the query args, too? – harshclimate Mar 27 '18 at 18:12
  • Okay, this works :) So let me understand: Will this list every year from 2018 on? – harshclimate Mar 28 '18 at 0:04
  • Actually, it orders the posts from the most recent to the older. It checks the publication year of each post, if we have not displayed it yet we show it. – Friss Mar 28 '18 at 4:56
  • Sorry, I'm just not that great at looking at php and knowing what it'll do. Sometimes I get lucky and can figure it out, but so, when this code runs it'll display the current year, the posts under the specified category, but when 2018 runs out and 2019 is upon us, will it keep the 2018 posts under the 2018 heading? Then start listing 2019 posts under a 2019 header? – harshclimate Mar 28 '18 at 12:32
  • Yes, that's it, as you described in your question. – Friss Mar 28 '18 at 12:34
0

Thanks for your help, Friss!

I added category_name to the query so I could draw down the photography category:

<?php $args = array( 'post_type' =>'post', 'posts_per_page' => -1, 'post_status' => 'publish', 'orderby' => 'post_date', 'order' => 'DESC', 'category_name' => 'photography' ); $photography_archive = new WP_Query( $args ); ?>

| improve this answer | |
  • Glad to help :) – Friss Mar 28 '18 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.