Hiển thị sản phẩm liên quan cùng Danh Mục
add_filter('woocommerce_related_products_args', 'filter_woocommerce_related_products_args');
function 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;
}
Hiển thị sản phẩm liên quan cùng Danh Mục Con
/**
* 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;
}