X

Adding Custom Post Types to wp_get_archives()

Snippets by IsItWP

Are you looking for a way to enable wp_get_archives to display your custom post types? While there’s probably a plugin for this, we have created a quick code snippet that you can use to add custom post types to wp_get_archives() in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_filter( 'getarchives_where' , 'ucc_getarchives_where_filter' , 10 , 2 ); 
function ucc_getarchives_where_filter( $where , $r ) { 
	$args = array( 'public' => true , '_builtin' => false ); 
	$output = 'names'; $operator = 'and';
	$post_types = get_post_types( $args , $output , $operator ); 
	$post_types = array_merge( $post_types , array( 'post','CUSTOM_POST_TYPE_NAME' ) ); 
	$post_types = "'" . implode( "' , '" , $post_types ) . "'";
	return str_replace( "post_type = 'post'" , "post_type IN ( $post_types )" , $where ); 
} 

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 27 best WordPress business themes for your website and 15 best content marketing tools and plugins for WordPress.

Comments   Leave a Reply

  1. 404

  2. Thanks for that..however I’m having a bit of difficulty with the actual link, if I now click on say “February”, it takes me to the non custom post type archives in february. Instead of the CPT posts for Feb.  i.e. the link is just /2012/02/ 

    1.  yes, archive list links to post type “post” yearly archive instead of cpt yearly archive

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!