-
-
Save deadlyhifi/5b7115d79e610f125a3c to your computer and use it in GitHub Desktop.
Here's my solution for newer WooCommerce, add this to functions.php and include this filter in post query in carousel or somewhere :p merry xmas!
/**
* GET RELATED PRODUCTS FROM DIRECT CATEGORY
*/
add_filter( 'woocommerce_product_related_posts', 'woocommerce_get_direct_related_products' );
function woocommerce_get_direct_related_products($args) {
global $woocommerce, $product;
// Related products are found from category
$cats_array = array(0);
// Get categories
$terms = wp_get_post_terms( $product->id, 'product_cat' );
//Select only the category which doesn't have any children
foreach ( $terms as $term ) {
$children = get_term_children( $term->term_id, 'product_cat' );
if ( !sizeof( $children ) )
$cats_array[] = $term->term_id;
}
// Don't bother if none are set
if ( sizeof( $cats_array ) == 1 ) return $args;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$limit = -1;
$post_ids = get_posts(array(
'orderby' => 'rand',
'posts_per_page'=> $limit,
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'post__not_in' => array( $product->get_id() ), //this is the way i remove current prod xd
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $cats_array
),
),
'fields' => 'ids', // Only get post IDs
));
// Alter the query
$args['post__in'] = $post_ids;
return $args;
}
Thanks @m16averick.
@m16averick - It's not working for me, but I have hierarchal categories. Can it be made to work that way or with tags?
I tested the code on my site.
I see no effect on how it works in related products. Probably because all the products also have the "Uncategorized" category. Should the code be changed to remove this category from the search for related products?
I'm using the DIVI theme, I don't wish it was a DIVI problem. What do you think?
Thanks
I find this plugin which is suitable for our requirement - Related Products for WooCommerce by WebToffee,
After installing the plugin you can able to display products based on category and tags. If you want to display products based on sub-category follow this tutorial. https://www.webtoffee.com/related-products-woocommerce-user-guide/#sub_category
I find this plugin which is suitable for our requirement - Related Products for WooCommerce by WebToffee, After installing the plugin you can able to display products based on category and tags. If you want to display products based on sub-category follow this tutorial. https://www.webtoffee.com/related-products-woocommerce-user-guide/#sub_category
Thanks alot
Sorry, this was done a few years ago and things might have changed. I’m not working on any woocom sites so can’t really check it out.