从WP_Query中排除WooCommerce产品类别

时间:2017-12-04 09:46:03

标签: php wordpress woocommerce categories product

我已将以下args定义为我的查询的一部分:

$args = apply_filters('woocommerce_related_products_args', array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
            array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
        )
    )
) );
$products = new WP_Query( $args );

我需要从查询中排除名为杂志(slug"杂志")或ID 351的类别。

我一直试图加入'category__not_in' => array('magazines'),所以它看起来像这样:

$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines'),
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );

但这似乎并没有起作用。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

产品类别是自定义分类product_cat

所以你需要用简单的tax_query这样做:

$args = apply_filters('woocommerce_related_products_args', 
    array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
             array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
            ),
        ),
        'tax_query'            => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug', // Or 'name' or 'term_id'
                'terms'    => array('magazines'),
                'operator' => 'NOT IN', // Excluded
            )
        )
    ) 
);

$products = new WP_Query( $args );

答案 1 :(得分:0)

您应该将category__not_in值用作此类数组

$query = new WP_Query( array( 'category__not_in' => array( 'magazines' ) ) );

详细信息请查看

WP_Query

所以请将您的代码更新到此

$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines')
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );

让我知道它是否适合您。