The client wanted to hand-pick which related products would be visible on the product pages. So I replaced ‘related products’ with ‘cross sells’.
Step 1: get the ids of the cross sell products using the ‘_crosssell_ids’ meta key.
<?php
/* crossells */
$crosssell_ids = get_post_meta( get_the_ID(), '_crosssell_ids' );
$crosssell_ids=$crosssell_ids[0];
?>
Step 2: Loop through the products by id
<?php
if(count($crosssell_ids)>0){
$args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'post__in' => $crosssell_ids );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?><a href='<?php the_permalink(); ?>'><?php
the_post_thumbnail( 'thumbnail' );
the_title();
?></a><?php
endwhile;
}
?>
16 Comments
Frederikvdbe
Finally a code that works!
Thanks for this!
Michael Levy
You’re Welcome! Best of luck.
eyeBoogies
Thanks Michael for sharing this code, it helped me out.
Olaf Lederer
Nice one!
I used your code to replace the query inside the related.php file and it works great.
How would you do this to use the up-sell feature on the cart page?
WooCommerce things this is the right place for cross selling 🙂
Seems to me more complicated if your cart has more than one order item.
Michalis Velonakis
Thank you very much for this post, you just saved my day! 🙂
Teodor Malmborg
Thanks a million. Can’t believe this feature was so hard to find.
Arun Verma
Exact code what i want, saved many hours.
Thanks for sharing nice piece of code.
Maugeri Antonino
Hi, can you describe where put this code?
which is the file to be edited?
Michael Levy
If you look at the single-product template, it lists the templates parts. Follow the trail, and find where you’d like to put it.
yejiel
Im super new to wordpress and woocomerce, and im having a really hard time understanding your code, but it looks exactly what im looking for, did you replaced the code inside related to yours o where?
Michael Levy
Hi Yejiel,
This code will display the cross-sells where it is placed. It could replace other content or be added to the page elsewhere.
The first part gets all the ids for the cross sells associated with the post.
The second part runs a WordPress loop that retrieves the data based on the ids and prints it.
Michael
Alex
Hello!
Is this also possible throught filters/hooks? So you don’t have to worry about theme updates that much.
Andrew
Amazing! Thanks for sharing this! Works like a charm.
Usman Ghani
Where to put that code? can you explain please. I mean in which file I had to put this code in?
Yaniv
Thanks, it works! Is there a way to display bigger images? (it is currently only getting the 150px thumbnails)
Michael Levy
The pulls the image here:
the_post_thumbnail( ‘thumbnail’ );
You can either change the size to:
– Another built-in size like “large”, or “medium”
– Channge the size of the thumbnail image in the admin
– Or create a custom size https://developer.wordpress.org/reference/functions/add_image_size/