Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Click tracking
Relevanssi Premium 2.16 introduced a new feature of click tracking. It allows you to see the effectiveness of the search,…
Keyword-based search blocking
Update: In Premium 2.15.0 and later versions, you can do spam blocking from Relevanssi settings. Just navigate to the Spam…
Pinning posts
Sometimes you want to get a specific post as the first result for a certain search, but Relevanssi doesn’t return…

Related Posts:

Currently there are no related posts available.

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed