Hello Namaste 🙏,

In one of our recent projects, we have a requirement to display months organized by year on the right side of the page. When a user clicks on a specific month, we need to use AJAX to fetch and display a list of blog posts published during that month. Additionally, if there are no posts for a particular month, we should disable that month.

To provide you with a clearer understanding, please refer to the screenshot below

 

To achieve this, we utilized MySQL queries, foreach loops, and arrays. Here’s the code snippet:

The resulting array will provide you with the necessary data. You can utilize it as per your requirements.

<?php
global $wpdb;
$query = "select date_format(post_date, '%Y-%b') as yearmonth
from ".$wpdb->prefix."posts
where post_type='post' and post_status='publish'
group by yearmonth
order by yearmonth DESC";
$result = $wpdb->get_results( $query );
$final_array = array();
foreach( $result as $row )
{
$yearmonth = explode( "-", $row->yearmonth );
$year = $yearmonth[0];
$month = $yearmonth[1];
$month_list = array(
"Jan" => false,
"Feb" => false,
"Mar" => false,
"Apr" => false,
"May" => false,
"Jun" => false,
"Jul" => false,
"Aug" => false,
"Sep" => false,
"Oct" => false,
"Nov" => false,
"Dec" => false,
);
if( !array_key_exists( $year, $final_array ) )
{
$final_array[$year] = $month_list;
}
$final_array[$year][$month] = true;
}
// OutPut
echo "<pre>";
print_r($final_array);
echo "</pre>";
Array
(
[2020] => Array
(
[Jan] => 1
[Feb] => 1
[Mar] =>
[Apr] =>
[May] =>
[Jun] =>
[Jul] =>
[Aug] =>
[Sep] =>
[Oct] => 1
[Nov] => 1
[Dec] =>
)
[2019] => Array
(
[Jan] =>
[Feb] =>
[Mar] =>
[Apr] =>
[May] =>
[Jun] =>
[Jul] =>
[Aug] =>
[Sep] => 1
[Oct] =>
[Nov] =>
[Dec] =>
)
[2018] => Array
(
[Jan] =>
[Feb] =>
[Mar] =>
[Apr] =>
[May] =>
[Jun] =>
[Jul] =>
[Aug] => 1
[Sep] =>
[Oct] =>
[Nov] =>
[Dec] =>
)
[2015] => Array
(
[Jan] =>
[Feb] =>
[Mar] =>
[Apr] => 1
[May] =>
[Jun] =>
[Jul] =>
[Aug] =>
[Sep] =>
[Oct] =>
[Nov] =>
[Dec] =>
)
)
?>