Woocommerce 3.0相关产品过滤

时间:2018-06-03 16:13:07

标签: mysql wordpress woocommerce

是否有办法从相关产品部分中排除具有特定值属性的产品。例如,我希望按类别划分相关产品,但属性为attribute_value('pa_season') = summer;

的产品除外

我尝试了这个,但它无法正常工作

add_filter( 'woocommerce_related_products_args', 'filter_related_products' );
function filter_related_products( $args ) {
    global $product;
    return array(
       'post_type'            => 'product',
       'ignore_sticky_posts'  => 1,
       'no_found_rows'        => 1,
       'posts_per_page'       => 4,
       'orderby'              => 'ASC',
       'post__not_in'         => array( $product->get_id() ),
       'tax_query'      =>     array(
              array(
                  'taxonomy' => 'pa_epoxi',
                  'field' => 'slug',
                  'terms' => 'autumn-winter'
              )
        )
    );
}
编辑:我发现我可以使用过滤器 woocommerce_product_related_posts_query编辑从数据库中获取相关产品的查询。

我尝试了以下代码:

add_filter( 'woocommerce_product_related_posts_query', function( $query ) {
    $query['where'] .= " AND t.term_id !=100";
    return $query;
});

但我收到错误报告:'where子句'

中的未知列't.term_id'

1 个答案:

答案 0 :(得分:0)

我设法通过使用过滤器woocommerce_product_related_posts_query排除了我想要的术语ID,并像这样编辑SQL查询:

function exclude_terms_from_related_products( $query ) {
    global $wpdb;
    $exclude_term_ids[0] = 100; // term_id
    $query['join']  .= " LEFT JOIN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( " . implode( ',', array_map( 'absint', $exclude_term_ids ) ) . ' ) ) AS exclude_join1 ON exclude_join1.object_id = p.ID';
    $query['where'] .= ' AND exclude_join1.object_id IS NULL';
    return $query;
}
add_filter( 'woocommerce_product_related_posts_query', 'exclude_terms_from_related_products' );