2
votes

I'm looking to output related products on my woocommerce cart page.

The function woocommerce_related_products() works perfectly when viewing a single product.

But when on shopping-cart.php, using this function returns an error:

Fatal error: Call to a member function get_related() on a non-object in /woocommerce/single-product/related.php

I tried including the function within the product loop:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    $product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

    if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters('woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
        woocommerce_related_products();
    }
}

This produced the same error.

Is it possible to do this where there are several products currently in question? I would happily pick a random product from the cart and output suggestions based on that.

1

1 Answers

1
votes

The problem is that the woocommerce_related_products() is supposed to be used in a loop (that's a WordPress-specific term). That function includes /woocommerce/single-product/related.php template inside which WooCommerce tries to reach global variables $product and $woocommerce_loop that are not defined where you are trying to execute the function.

I would advice you to open file /woocommerce/single-product/related.php, see how related products are retrieved and write some more custom code to get related products displayed outside loop.