WordPress posts sorted by category and year

I was in a long google search trying to find a solution to this ... I am creating a cv manager theme using the WordPress installation to manage content. I managed to organize all WP posts in categories, but I would also like to list these posts per year. I currently have this:

<?php // Categories
         $cvm_cat_args = array('orderby' => 'name', 'order' => 'ASC' ); 
         $categories = get_categories($cvm_cat_args); ?>

<?php foreach($categories as $category) : ?>

<?php // Posts in category
         $cvm_post_args = array( 'showposts' => -1, 'category__in' => array($category->term_id), 'caller_get_posts'=>1, 'order' => 'ASC' );
         $posts = get_posts($cvm_post_args); ?>

<?php if ($posts) : ?>

<h1><?php echo $category->name ?></h1>

<?php foreach($posts as $post) : ?>
<?php setup_postdata($post); ?>

<h3><?php the_title();  ?></h3>
<small><?php the_time(); ?></small>
<?php the_excerpt() ?>

<?php endforeach; ?>

<?php endif; ?>

<?php endforeach; ?>

I went in cycles on how to display messages in a year order in a category so that the result would be something like this:

<h1>Category Name 1</h1>

<h2>2010</h1>

<h3>Post name 1</h3>
<p>Excerpt...</p>

<h3>Post name 2</h3>
<p>Excerpt...</p>


<h2>2009</h1>

<h3>Post name 3</h3>
<p>Excerpt...</p>

<h3>Post name 4</h3>
<p>Excerpt...</p>

<h1>Category Name 2</h2>
etc

Any help would be greatly appreciated.

Thank!

+3
source share
1 answer
<?php $year = ''; ?>
<?php foreach($posts as $post) : ?>
<?php setup_postdata($post); ?>
<?php if (get_the_time('Y') != $year): ?>
<?php $year = get_the_time('Y'); ?>
<h2><?php echo $year; ?></h2>
<?php endif; ?>

<h3>Post name 1</h3>
<p>Excerpt...</p>

<h3>Post name 2</h3>
<p>Excerpt...</p>

<?php endforeach; ?>
0
source

Source: https://habr.com/ru/post/1764329/


All Articles