Thanks to Rarst for the tip.
Here is the code I came up with to accomplish redirects for two similar taxonomy/post type set ups.
This basically does what I indicated in the OP. If I hit a single post with a top-level term assigned to it, the url will go from
domain/series/post/
to
domain/series/
It simply strips the post's slug from the end of the url.
Obviously, the CPTs, taxonomies and rewrites have to be set up properly to work with this.
I added the $type
parameter to the theme_perform_redirect()
function so that I can add functionality to it later for other types of redirects.
function theme_perform_redirect($post, $taxonomy, $type) {
if ($type == 'top-level') {
$top_level_terms = get_top_level_term_ids( $taxonomy );
$post_terms = wp_get_post_terms( $post->ID, $taxonomy );
if ( in_array($post_terms[0]->term_id, $top_level_terms)) {
// This is the main/top post, redirect it to the archive
$to_strip = $post->post_name;
$permalink = get_permalink( $post->ID );
$go_here = str_replace($to_strip."/", "", $permalink);
wp_redirect( $go_here );
exit();
}
}
}
function theme_redirects() {
global $post;
if ( is_single() ) {
if (is_singular( 'cartoon-series' )) {
heman_perform_redirect($post, 'cartoon-features', 'top-level');
} else if (is_singular( 'movies' )) {
heman_perform_redirect($post, 'movie-features', 'top-level');
}
}
}
add_action( 'template_redirect', 'theme_redirects' );
Note that get_top_level_term_ids()
is my own function. It just grabs all the terms with a parent of 0....just in a neater package. :-)
Thanks!