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…

Read More

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?

Related posts

1 comment

  1. 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:

Comments are closed.