Posted on

Automatic redirects to category archives

While Relevanssi Premium can return taxonomy terms as search results, sometimes sending the searcher directly to the category archive is better. This is especially true for WooCommerce sites, where displaying taxonomy terms in search results pages is complicated.

Relevanssi Premium has a redirect feature you can use to redirect searches to specific pages. This is a good solution, but manually maintaining the redirects can be a chore if there are many categories. Fortunately, this is something that can be automated.

Here’s one solution:

add_action( 'saved_term', function() {
    $redirects    = get_option( 'relevanssi_redirects', array() );
    $product_cats = get_categories( 'taxonomy=product_cat' );

    $existing_redirects = wp_list_pluck( $redirects, 'url' );
    foreach ( $product_cats as $cat ) {
        $url = get_category_link( $cat->term_id );
        if ( ! in_array( $url, $existing_redirects, true ) ) {
            $redirects[] = array(
                'url'     => $url,
                'query'   => $cat->name,
                'partial' => false,
                'hits'    => 0,
            );
        }
    }

    update_option( 'relevanssi_redirects', $redirects );
} );

This function runs on the saved_term action hook, which triggers whenever a taxonomy term is saved. It checks your redirects and adds missing product_cat category redirects. This will make sure your redirection settings are always up to date. To create the first redirects, you need to add this function to your site and then save a product category term.

This does not remove redirects for non-existing categories, so that is something you need to maintain manually.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *