
Using WordPress Archive Widget to Display Customized Archives
- December 8, 2016
- Leave a comment
In WordPress you can easily display archives, on a monthly or yearly basis, as a single link using the default archive widget. However to get a customized display, you need to rewrite the code. In this article, we will explain how to display lists of archives on a monthly basis under a yearly heading.
You need to add the following PHP code to functions.php file of your active theme. The code snippet below generates a list of monthly achives with separated by yearly headings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function pt_year_wise_monthly_archive(){ global $wpdb; $year_prev = ''; $year_current = ''; $where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish' AND post_date <= now()" ); $join = apply_filters( 'getarchives_join', '' ); $months = $wpdb->get_results( "SELECT YEAR(post_date) AS year, MONTH(post_date) AS numMonth, DATE_FORMAT(post_date, '%M') AS month, count(ID) as post_count FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" ); $html = ''; foreach($months as $month) : $year_current = $month->year; if ($year_current != $year_prev){ if ($year_prev != null){ $html .= '</ul>'; } $html .= '<h3>'.$month->year.'</h3>'; $html .= '<ul class="arc-list">'; } $html .= '<li>'; $html .= '<a href="'.get_bloginfo('url').'/'.$month->year.'/'.date("m", strtotime($month->month)).'">'; $html .= '<span class="arc-month">'.$month->month.'</span>'; $html .= '<span class="arc-count">'.$month->post_count.'</span>'; $html .= '</a>'; $html .= '</li>'; $year_prev = $year_current; endforeach; $html .= '</ul>'; $html .= '<style> .arc-list a { display:block;} .arc-list li { list-style:none; } </style>'; echo $html; } |
Place the callback function pt_year_wise_monthly_archive() in you template file where you want to display the archive listing widget e.g sidebar.php. The function will output html of archive listing as explained.
You are done!
For a novice, to where does one add the custom PHP code?
Hello Alex,
Please add the above code snippet in your theme’s functions.php file and use the callback pt_year_wise_monthly_archive() where you want to display the customize archive widget.
Thanks for reaching us out. Let us know if you need any other assistance from us.
Regards,
Abdullah | WP Plugin Developer
Email: support@presstigers.com