WordPress.org

Forums

WooCommerce - excelling eCommerce
Solved! Redirect category if it only has a single product. (1 post)

  1. António Pinto
    Member
    Posted 1 year ago #

    I wanted to redirect a category to the product page if it only ad a single product.

    I searched various hacks, but none worked like I wanted (most did not even worked at all).

    After messing a bit I found this sollution:

    Add the following code to your fucntions.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;
    
    }

    This is an adapted sollution from: woocommerce redirect category with single product to product page? (7 posts)

    I hope this helps.

    https://wordpress.org/plugins/woocommerce/

Topic Closed

This topic has been closed to new replies.

About this Plugin

  • WooCommerce - excelling eCommerce
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic

Tags

No tags yet.