Last active
February 22, 2020 06:59
-
-
Save wpbean/d831133e1e0d155df38b863882ef2fa7 to your computer and use it in GitHub Desktop.
WPB WooCommerce Related Products Slider - Related Products by Sub categories only
This file contains 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 | |
/** | |
* Related Products by Sub categories only | |
*/ | |
add_filter('wpb_wrps_related_products_args', 'wpb_wrps_filter_woocommerce_related_products_args'); | |
function wpb_wrps_filter_woocommerce_related_products_args($args) | |
{ | |
global $post; | |
// get the cats this product is in | |
$terms = get_the_terms($post->ID, 'product_cat'); | |
// if there is only one category jump out. | |
if (count($terms) === 1) { | |
return $args; | |
} | |
$cats = array(); | |
// remove anything that is a parent cat | |
foreach ($terms as $k => $term) { | |
if ($term->parent === 0) { | |
unset($terms[$k]); | |
} else { | |
// build list of terms we do want (children) | |
$cats[] = $term->term_id; | |
} | |
} | |
$post_ids = get_posts(array( | |
'post_type' => 'product', | |
'numberposts' => -1, // get all posts. | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'product_cat', | |
'field' => 'term_id', | |
'terms' => $cats, | |
), | |
// Remove current product | |
array( | |
'taxonomy' => 'product_cat', | |
'field' => 'term_id', | |
'terms' => $post->ID, | |
'operator' => 'NOT IN', | |
), | |
), | |
'fields' => 'ids', // Only get post IDs | |
)); | |
// Alter the query | |
$args['post__in'] = $post_ids; | |
return $args; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment