Skip to content

Commit 2827055

Browse files
authored
Redirect single term filter pages to their canonical archive URLs (#194)
1 parent 71624dd commit 2827055

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

source/wp-content/themes/wporg-showcase-2022/functions.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
add_filter( 'excerpt_more', __NAMESPACE__ . '\modify_excerpt_more' );
2828
add_filter( 'query_loop_block_query_vars', __NAMESPACE__ . '\modify_query_loop_block_query_vars', 10, 2 );
2929
add_filter( 'wporg_noindex_request', __NAMESPACE__ . '\set_noindex' );
30+
add_action( 'template_redirect', __NAMESPACE__ . '\redirect_term_archives' );
3031
add_action( 'wp', __NAMESPACE__ . '\jetpack_remove_rp', 20 );
3132
add_filter( 'jetpack_images_get_images', __NAMESPACE__ . '\jetpack_fallback_image', 10, 3 );
3233
add_filter( 'jetpack_related_posts_display_markup', __NAMESPACE__ . '\jetpack_related_posts_display', 10, 4 );
@@ -584,3 +585,28 @@ function jetpack_redirect_submission_form( $redirect ) {
584585
}
585586
return $redirect;
586587
}
588+
589+
/**
590+
* Redirect category and tag archives to their canonical URLs.
591+
*
592+
* This prevents double URLs for every category/tag, e.g.,
593+
* `/archives/?tag[]=cuisine` and `/tag/cuisine/`.
594+
*/
595+
function redirect_term_archives() {
596+
global $wp_query;
597+
$terms = get_applied_filter_list( false );
598+
// True on the `/tag/…` URLs, and false on `/archive/?tag…` URLs.
599+
$is_term_archive = is_tag() || is_category() || is_tax();
600+
601+
// If there is only one term applied, and we're not already on a term
602+
// archive, redirect to the main term archive URL.
603+
if ( count( $terms ) === 1 && ! $is_term_archive ) {
604+
$url = get_term_link( $terms[0] );
605+
// Pass through search query.
606+
if ( isset( $wp_query->query['s'] ) ) {
607+
$url = add_query_arg( 's', $wp_query->query['s'], $url );
608+
}
609+
wp_safe_redirect( $url );
610+
exit;
611+
}
612+
}

0 commit comments

Comments
 (0)