Fetch year-wise month list if have post in a particular month in WordPress

Posted on

Hey Namaste ,

In a one of the recent project, We have a requirement like need to display year-wise months at the right side of the page and on click any month have to display a list of the blog post of that month using ajax and have to disable month if there no any posts.

Check below screenshot for the better understanding.

Screenshot_3

For this, We used MySQL query,foreach and array. Please check below code.

If have a blog post in the month then values will set true.

Below is array output, you can use it anyplace as per your need.


Leave a Reply

Your email address will not be published. Required fields are marked *

<?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] =>