Skip to content

Instantly share code, notes, and snippets.

@ruturajpatki
Last active May 24, 2019 08:39
Show Gist options
  • Select an option

  • Save ruturajpatki/cfeb0395012c5d2f6233d6529878c03a to your computer and use it in GitHub Desktop.

Select an option

Save ruturajpatki/cfeb0395012c5d2f6233d6529878c03a to your computer and use it in GitHub Desktop.
Redirect WooCommerce Category to Product page if it has only 1 product in it.
<?php
/* Redirect if there is only one product in the category */
add_action( 'wp_head', 'woocom_redirect_if_single_product_in_category', 10 );
function woocom_redirect_if_single_product_in_category() {
global $wp_query;
if (is_product_category()) {
$cat_obj = $wp_query->get_queried_object();
$catcount = $cat_obj->count;
if ($catcount > 1 ){
return;
}
$product = new WC_Product($wp_query->post->ID);
if($product){
if ( $product->is_visible() ){
$link = get_permalink($product->post->id);
wp_redirect($link, 302 );
exit;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment