Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and display related products in WooCommerce

I have included WooCommerce related products in a theme with the following:

<?php wc_get_template( 'single-product/related.php' ); ?>

This has been copied into my template and is executing.

However, even though I have added various upsells with this product the $related_products variable (used in the loop) is NULL. Is there any other variables at play in order to start showing these related products?

like image 295
Squiggs. Avatar asked Nov 17 '18 22:11

Squiggs.


People also ask

What is a related product display?

Related Products are those products that share the same tags or categories. They are usually displayed on single product pages. For example, if you're viewing a shirt, then you'll also see 3-4 shirts having the same category or tags, as related products.

What is linked products in WooCommerce?

WooCommerce linked products functionality allows to stimulate customers' purchasing experience and increase profitability of website with effective cross and upselling techniques.

How do I get a list of products in WooCommerce?

In the WordPress admin, go to WooCommerce > Settings > Products > Product tables. Add your license key and read through all the settings, choosing the ones that you want for your WooCommerce all products list. Now create a page where you want to list all products in a table (Pages > Add New.


1 Answers

You need much more than that (and the post_id need to be a product):

global $product; // If not set…

if( ! is_a( $product, 'WC_Product' ) ){
    $product = wc_get_product(get_the_id());
}

$args = array(
    'posts_per_page' => 4,
    'columns'        => 4,
    'orderby'        => 'rand',
    'order'          => 'desc',
);

$args['related_products'] = array_filter( array_map( 'wc_get_product', wc_get_related_products( $product->get_id(), $args['posts_per_page'], $product->get_upsell_ids() ) ), 'wc_products_array_filter_visible' );
$args['related_products'] = wc_products_array_orderby( $args['related_products'], $args['orderby'], $args['order'] );

// Set global loop values.
wc_set_loop_prop( 'name', 'related' );
wc_set_loop_prop( 'columns', $args['columns'] );

wc_get_template( 'single-product/related.php', $args );

Or in a shorter way (which will give you the same):

global $product;

if( ! is_a( $product, 'WC_Product' ) ){
    $product = wc_get_product(get_the_id());
}

woocommerce_related_products( array(
    'posts_per_page' => 4,
    'columns'        => 4,
    'orderby'        => 'rand'
) );

Both ways are tested and works…

like image 62
LoicTheAztec Avatar answered Oct 10 '22 10:10

LoicTheAztec