DEV Community

Yuvraj Khavad
Yuvraj Khavad

Posted on

1

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

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.

<?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] =>
)
)
?>
view raw month_list.php hosted with ❀ by GitHub

Top comments (2)

Collapse
 
ajulcab profile image
AHIEZER JULCA BLAS β€’

good solution

Collapse
 
yuvrajkhavad profile image
Yuvraj Khavad β€’

Thank You @ajulcab

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more