How to redirect directly to the product page when the category only holds one item

How to redirect directly to the product page when the category only holds one item

// REDIRECT TO SINGLE PRODUCT WHEN ONLY ONE PRODUCT IS FOUND IN THE CATEGORY
add_action( 'template_redirect', function () {
  global $wp_query;

  // Redirect to the product page if we have a single product
  if ( is_product_category() && $wp_query->found_posts == 1) {
    $product = wc_get_product( $wp_query->posts[0]->ID );

    if ( $product && $product->is_visible() ) {
      wp_safe_redirect( get_permalink( $wp_query->posts[0]->ID ), 302 );
      exit;
    }
  }
} );

 


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.