我已经尝试过这段代码并正确地为我工作:
add_filter( 'woocommerce_product_related_posts', 'my_custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Related products are found from category and tag
$tags_array = array(0);
$cats_array = array(0);
// Get tags
$terms = wp_get_post_terms($product->id, 'product_tag');
foreach ( $terms as $term ) $tags_array[] = $term->term_id;
// Get categories
$terms = wp_get_post_terms($product->id, 'product_cat');
foreach ( $terms as $key => $term ){
$check_for_children = get_categories(array('parent' => $term->term_id, 'taxonomy' => 'product_cat'));
if(empty($check_for_children)){
$cats_array[] = $term->term_id;
}
}
// Don't bother if none are set
if ( sizeof($cats_array)==1 && sizeof($tags_array)==1 ) return array();
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => $limit,
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $cats_array
),
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => $tags_array
)
)
) );
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
但是如果我在“运动”>“耐克”>“鞋子”中有一些产品,它会在“耐克”中显示相关产品,而不是在“鞋子”中显示相关产品。我需要在具有相同子类别的单个产品页面中随机显示相关产品(最后一个类别 - 没有子 - 例如“鞋子”)
将上述代码替换为以下代码片段以实现上述任务 -
function wc_related_products_by_last_available_depth_term( $related_posts, $product_id, $args ) {
$product = wc_get_product( $product_id );
$terms = wp_get_post_terms( $product_id, 'product_cat' );
$hierarchy = array();
$cat_id = '';
// find the depth of terms
foreach ( $terms as $key => $term ) {
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
if( $ancestors && count( $ancestors ) > 1 ) {
$hierarchy[$term->term_id] = max($ancestors);
}elseif( $ancestors ) {
$hierarchy[$term->term_id] = $ancestors[0];
}
$cat_id = $term->term_id;
}
// if level of depth term available replace $cat_id
if( $hierarchy ){
$cat_id = max( array_keys( $hierarchy ) );
}
$related_posts = get_posts( array(
'post_type' => 'product',
'post_status' => 'publish',
'fields' => 'ids',
'posts_per_page' => -1,
'exclude' => array( $product_id ),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => array( $cat_id )
)
)
));
return $related_posts;
}
add_filter( 'woocommerce_related_products', 'wc_related_products_by_last_available_depth_term', 99, 3 );
代码转到您活动主题的functions.php