Skip to content
Advertisement

How to upsell product in woocoomerce based on last product’s variation

I hope someone with more coding knowledge nouse will know more on how to tackle this little upsell issue I have in WordPress.

The idea is in a side cart, based on the last product’s variation, it will show an upsell product in the side cart. Currently I am using a Woo side cart plugin that displays a random upsell in the side cart but I want to overwrite this via code.

So in my php snippets, I have written the code where it takes the last product’s variation as so:

global $woocommerce;

//get cart items
$items = $woocommerce->cart->get_cart();

$ids = array();
foreach($items as $item => $values) { 
        $_product = $values['data']->post; 
        //push each id into array
        $ids[] = $_product->ID; 
} 

//get last product id
$last_product_id = end($ids);

//get product variation details
$variations = get_variation_data_from_variation_id( $last_product_id );

//function to get product variation
    function get_variation_data_from_variation_id( $item_id ) {
        $_product = new WC_Product_Variation( $item_id );
        $variation_data = $_product->get_variation_attributes();
        //return variation detail
        return woocommerce_get_formatted_variation( $variation_data, true ); 
    }

So now the idea is that based on that variation, display any product that is higher in price with the same variation to upsell. If these isn’t one then display a product with same variation but lower price. If there isn’t one then display a random random upsell of any product.

So example: I add to cart a coffee bag which is “250g and wholebean” for £29.99. For an upsell, I hope it displays a product which is the same “250g and wholebean” and the price is £39.99.

So I have two issues.

1: How to code the upsell to match the above scenario 2: I have a side cart that contains a random upsell. I need to overwrite this random upsell with this code but now sure how to do that?

Please view the site here so you can see: https://shop.balancecoffee.co.uk/

Thank you

Advertisement

Answer

All products in WooCommerce have a configurable upsell in the CMS – this can be accessed on $product->get_upsell_ids(). This should be used to generate upsell products based on your product in the carts.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement