Custom Post Type Archive

I have dug all over the internet for a query like this one!

This will generate the get_archives_link needed to link to your Custom Post Type year/month url.

Simply update the string with the Custom Post Type name and Category. This will create a series of links to the default archive page, and you can add this filter to the sidebar so the content can be sorted.

$querystr = "SELECT YEAR(post_date) AS 'year', MONTH(post_date) AS 'month' , count(ID) as posts FROM $wpdb->posts INNER JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE $wpdb->term_taxonomy.term_id != 12 AND $wpdb->term_taxonomy.parent != 12 AND $wpdb->term_taxonomy.taxonomy = 'staff_category' AND $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'staff_posts' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC";

$years = $wpdb->get_results($querystr);

foreach ( (array) $years as $year ) {
	$url = get_month_link( $year->year, $year->month );
	$date =mysql2date('F o', $year->year.'-'.$year->month, $translate = true);
	echo get_archives_link($url, $date, 'html','<li>',' (' . $year->posts .')</li>');

Sourced here.

For more flexibility, and to link directly to your Custom Post Type content, use the query below, and adjust the post type, and URL to match your content.  The update archive.php to match your post type name (in this case, archive-staff_posts.php and the months will be filterable automatically.

This will only bring in data for your custom post type.

<ul class="cat_sort">
	<h2>Search by Month<img src="<?php bloginfo('stylesheet_directory'); ?>/img/down.png" /></h2>
	<?php $blogtime = date('Y');
	$prev_limit_year = $blogtime - 1;
	$prev_month = '';
	$prev_year = '';
	$args = array(
	         'posts_per_page' => -1,
	         'post_type' => 'staff_posts'
	$postsbymonth = new WP_Query($args);
	while($postsbymonth->have_posts()) {
							    if(get_the_time('F') != $prev_month || get_the_time('Y') != $prev_year && get_the_time('Y') == $prev_limit_year) {
							                <li><a href="<?php bloginfo('url');?>/<?php echo get_the_time('Y'); ?>/<?php echo get_the_time('m'); ?>/staff_posts"><?php echo get_the_time('F Y'); ?></a></li>
										<?php } ?>
    $prev_month = get_the_time('F');
    $prev_year = get_the_time('Y');
} ?>

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.