Last active
December 21, 2023 00:24
-
-
Save SirDarcanos/ac836999f211a7ef82aa9e5c09e8b304 to your computer and use it in GitHub Desktop.
WooCommerce Related Products: What and How to Improve Them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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