How to redirect custom post type archive to first term of associated taxonomy?

I have a custom post type ‘countries’ and a taxonomy ‘cities’.

My cities are: boston, new york…

I want my archive-countries.php redirect to the first term taxonomy.

I mean, if my URL is www.example.com/countries this should redirect to www.example.com/cities/boston.

How can I do this?

Solutions Collecting From Web of "How to redirect custom post type archive to first term of associated taxonomy?"

If you know you’re loading the right template, redirect to your first term of the specified taxonomy:

function wpse_135306_redirect() {
    $cpt = 'countries';
    if (is_post_type_archive($cpt)) {
        $tax = 'cities';
        $args = array(
            'orderby' => 'id', // or 'name' or whatever
        );
        $cities = get_terms($tax, $args);
        if (count($cities)) {
            wp_redirect(get_term_link(reset($cities), $tax));
            exit();
        }
    }
} // function wpse_135306_redirect
add_action('template_redirect', 'wpse_135306_redirect');

References:

  • template_redirect
  • is_post_type_archive
  • get_terms
  • wp_redirect
  • get_term_link