Variable Visions

Wordpress and Woocommerce redirect to a product page from categories with a single product

Published Thu. Sep. 05, 2019

// REDIRECT TO SINGLE PRODUCT PAGE FROM CATEGORY LIST WITH ONLY ONE ITEM

add_action( 'template_redirect', 'single_product_in_category', 10 );
function single_product_in_category() {
if ( is_product_category() ){
$category_name = sanitize_title( woocommerce_page_title( false ) );
$args = array(
"post_type" => "product",
"posts_per_page" => -1,
"product_cat" => $category_name
);
$posts = new WP_Query( $args );
if( count( $posts->posts ) == 1 ){
$single_post_ID = $posts->posts;
$ID = $single_post_ID[0]->ID;
wp_redirect( get_permalink( $ID ) );
}
}
}