Skip to content

Instantly share code, notes, and snippets.

@nerrad
Created October 28, 2012 17:52
Show Gist options
  • Save nerrad/3969275 to your computer and use it in GitHub Desktop.
Save nerrad/3969275 to your computer and use it in GitHub Desktop.
Have category archive pages display only posts in a certain custom post type
/**
* This could be extrapolated and used for tags or any other taxonomy really.
*/
add_action('init', 'category_cpt_rewrites');
function category_cpt_rewrites() {
$custom_post_types = array('video', 'audio', 'photo', 'file'); //some example post types
foreach ( $custom_post_types as $post_type ) {
$rule = '^' . $post_type . '/category/(.+?)/?$';
$rewrite = 'index.php?post_type=' . $post_type . '&category_name=$matches[1]';
add_rewrite_rule($rule,$rewrite,'top');
}
}
//make sure you flush rules
//this will take the following url structure (video cpt as an example, and politics as a category example) -> video/category/politics and return posts belonging to the politics category that are in the "video" custom post type.
//note that if you want this to be truly effective you'll want to make a custom "the_category()" or similar template function to return the correct url structure for a category list belonging to a custom post type post.
@bassscape
Copy link

This code is awesome! Previously I have only used the standard cpt url rewrites. I was thrilled to see this code work straight out of the box after simply switching in my cpt url rewrites for the $custom_post_types variable. Thanks!

@bassscape
Copy link

I have just realised i can't get pagination working on the rewritten category archives using the category.php template. Using previous_posts_link results in a 404:
previous_posts_link( 'Browse newer posts »' );
Still working on it.....

@bassscape
Copy link

I got it working by add in another rewrite rule for paged archives after page 1:
$rule = '^' . $post_type . '/category/(.+?)/page/([0-9]+)?$';
$rewrite = 'index.php?post_type=' . $post_type . '&category_name=$matches[1]&paged=$matches[2]';
add_rewrite_rule($rule,$rewrite,'top');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment