Search code examples
phpwordpresswoocommerceproductcustom-taxonomy

Replace Upsells with products from a specific product category in Woocommerce 3


I have the following case - So far I've always set the Upsell products custom, 1 by 1, as choosing a product category in the admin is not possible.

Now after a big cleaning of products that are no longer available, there are many product pages on the site with 1, 2 or 3 instead of the default number of 4 Upsell products, which breaks the design.

Is there a way to replace those upsells with products from a specific product category?

Any help is appreciated.


Solution

  • To replace woocommerce upsells by products from a specific product category use the following code (where you will define your product category(ies) slug(s)):

    add_filter( 'woocommerce_product_get_upsell_ids', 'custom_upsell_ids', 20, 2 );
    function custom_upsell_ids( $upsell_ids, $product ){
        // HERE define your product categories slugs in the array
        $product_categories = array( 't-shirts' ); // <=====  <=====  <=====  <=====  <=====
    
        // Return the custom query
        return wc_get_products( array(
            'status'    => 'publish', // published products
            'limit'     => 4, // 4 products
            'category'  => $product_categories, // Product categories
            'orderby'   => 'rand', // Random order
            'exclude'   => array( $product->get_id() ), // Exclude current product
            'return'    => 'ids', // Query returns only IDs
        ) );
    }
    

    Code goes in function.php file of the active child theme (or active theme). Tested and works.

    The query is set to display 4 products from a specific product category in a random order (excluding the current product).

    Official documentation: The wc_get_products() and WC_Product_Query