Programming, WordPress

Get the list of year associated with the posts

WordPress has a global object variable $wpdb, which communicates with the WordPress database. We can read more about $wpdb in Codex.

To get the list of the year in the posts, you can do the following :

<ul>
<?php
global $wpdb;
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" );
foreach($years as $year):?>
  <li> <?=$year->year?></li>
 <?php endforeach;?>
</ul>

 

In the aforementioned code, if you wish to get the year associated with the custom post type update the post_type name with your custom post type.

 

Views: 39

Standard