Skip to content

Instantly share code, notes, and snippets.

@brandonkramer
Last active September 1, 2021 16:47
Show Gist options
  • Save brandonkramer/eab0a691f4fd5e6dec6314ee3cabd54c to your computer and use it in GitHub Desktop.
Save brandonkramer/eab0a691f4fd5e6dec6314ee3cabd54c to your computer and use it in GitHub Desktop.
WooCommerce: If a parent category has only one subcategory then it will automatically redirect to that subcategory.
<?php
add_action( 'template_redirect', function () {
global $wp_query;
if ( is_archive() ) {
$queried_object = get_queried_object();
if (
isset( $queried_object->taxonomy ) &&
isset( $queried_object->term_id ) &&
$queried_object->taxonomy === 'product_cat' &&
count( get_term_children( $queried_object->term_id, 'product_cat' ) ) === 1 ) {
wp_safe_redirect( get_term_link( get_term_children( $queried_object->term_id, 'product_cat' )[0], 'product_cat' ), 302 );
exit;
}
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment