I found this great solution to show related products based on product attributes, but additionally we want to do the same for upsells.
What I've tried so far doesn't work as I believe we have to add some additional information as the related_products function is not the same as upsell.
add_filter( 'woocommerce_upsell_products', 'upsell_products_by_attribute', 10, 3 ); function upsell_products_by_attribute( $upsells, $product_id, $args ) { $taxonomy = 'pa_attribute'; $term_slugs = wp_get_post_terms( $product_id, $taxonomy, ['fields' => 'slugs'] ); if ( empty($term_slugs) ) return $upsells; $posts_ids = get_posts( array( 'post_type' => 'product', 'ignore_sticky_posts' => 1, 'posts_per_page' => 6, 'post__not_in' => array( $product_id ), 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $term_slugs, ) ), 'fields' => 'ids', 'orderby' => 'rand', ) ); return count($posts_ids) > 0 ? $posts_ids : $upsells; }
So I'm wondering if it's possible to do the same thing with the upsell part.
You can remove the default action hook
woocommerce_after_single_product_summary
and re-add it and you can customize theupsells
products. Check the code below. The code will go into your active theme's functions.php file.Change
$taxonomy = 'pa_color';
to your custom taxonomy.