Skip to content

Instantly share code, notes, and snippets.

@SiR-DanieL
Last active December 21, 2023 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiR-DanieL/ac836999f211a7ef82aa9e5c09e8b304 to your computer and use it in GitHub Desktop.
Save SiR-DanieL/ac836999f211a7ef82aa9e5c09e8b304 to your computer and use it in GitHub Desktop.
WooCommerce Related Products: What and How to Improve Them
<?php
/**
* @snippet Get Related Products by Attributes
* @author Nicola Mustone
* @author_url https://nicolamustone.blog/2023/12/21/improve-woocommerce-related-products-recommendations/
* @tested-up-to WooCommerce 8.4.X
*/
add_filter( 'woocommerce_related_products', 'nm_realted_products_by_attributes', 10, 3 );
function nm_realted_products_by_attributes( $related_posts, $product_id, $args ) {
$product = wc_get_product( $product_id );
$attributes = array( 'pa_attribute_1', 'pa_attribute_2', 'pa_attribute_3' );
$new_related_products = array();
foreach( $attributes as $attribute ) {
$terms = $product->get_attribute( $attribute );
if ( ! empty( $terms ) ) {
$new_related_products = array_merge( $new_related_products, nm_get_related_products( $product_id, $attribute, $terms ) );
}
}
if ( count( $new_related_products ) < 4 ) {
$related_posts = array_slice( array_merge( $new_related_products, $related_posts ), 0, 4 );
} else {
$related_posts = array_slice( $new_related_products, 0, 4 );
}
return $related_posts;
}
function nm_get_related_products( $product_id, $attribute, $terms ) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'post__not_in' => array( $product_id ),
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => $attribute,
'field' => 'name',
'terms' => array_map( 'trim', explode( ',', $terms ) ),
),
),
);
$query = new WP_Query( $args );
$related_products = wp_list_pluck( $query->posts, 'ID' );
return $related_products;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment