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. |
This comment has been minimized.
This comment has been minimized.
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: |
This comment has been minimized.
This comment has been minimized.
I got it working by add in another rewrite rule for paged archives after page 1: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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!