Last active
December 28, 2020 04:15
-
-
Save YuvrajKhavad/b9c3458e1940d8570f2a294ce8055237 to your computer and use it in GitHub Desktop.
Fetch year-wise month list if have posts in particular month in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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] => | |
) | |
) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment