PHP Snippet for Redirecting Taxonomy Archives to Filtered Archive Pages

Description/Instructions

This PHP snippet is perfect for those looking to redirect users from individual term feeds (e.g., taxonomy archives) to a main listing page with specific filters applied. By implementing this, you can ensure a consistent user experience where all related content is displayed on a single archive page, filtered by the selected term. Just replace the placeholders with your actual taxonomy names, archive URL, and query parameters. It’s a great solution for streamlining navigation and keeping your users engaged on your main listing page

Instructions

How to Use:

  1. Replace taxonomy_name1, taxonomy_name2, etc. with your actual taxonomy names.
  2. Replace /archive/ with the URL of your archive page.
  3. Adjust the query parameters (terms-param1, terms-param2, etc.) to match the URL structure you need.
  4. Use get_queried_object()->slug to dynamically insert the term slug into the URL.

add_action('template_redirect', 'redirect_taxonomy_to_archive');
function redirect_taxonomy_to_archive() {
// Example: Redirect for taxonomy_name1
if (is_tax('taxonomy_name1')) {
$term = get_queried_object();
$archive_url = home_url('/archive/') . '?type=your_post_type&terms-param1=' . $term->slug;
wp_redirect($archive_url);
exit();
}

// Example: Redirect for taxonomy_name2 with multiple parameters
if (is_tax('taxonomy_name2')) {
$term = get_queried_object();
$archive_url = home_url('/archive/') . '?type=your_post_type&terms-param2=value&terms-param3=' . $term->slug;
wp_redirect($archive_url);
exit();
}

// Example: Redirect for taxonomy_name3
if (is_tax('taxonomy_name3')) {
$term = get_queried_object();
$archive_url = home_url('/archive/') . '?type=your_post_type&terms-param4=' . $term->slug;
wp_redirect($archive_url);
exit();
}

// Add more taxonomies as needed following the same pattern
}

  • PHP
Copy Code

Let's Chat About this Snippet