Redirect to archive is single post has a certain term assigned to it?

I want to redirect any single post to its taxonomy term’s archive page if it has a specific term assigned to it.

So, if a post of a term “series” at:
I want to redirect that single post back to:

I’ve tried working with php’s header() function, but I know that needs to be used before any other headers are sent. I can’t seem to detect the terms AND use header() in the same place.

Any help is greatly appreciated!

Solutions Collecting From Web of "Redirect to archive is single post has a certain term assigned to it?"

There is a template_redirect hooks which is perfectly suitable for task like this.

  1. Hook into template_redirect
  2. Check your context (is_single(), etc)
  3. Redirect with wp_safe_redirect() (if it’s inside a site)
  4. die() to prevent execution from proceeding

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

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 );

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. 🙂