从 WooCommerce 相关产品自定义 WP 查询中删除缺货产品

Remove out of stock products from WooCommerce related products custom WP query

你好,我想根据我的自定义查询显示相关产品,但我只想显示 'in_stocks' 产品和 meta_query 不适用于 tax_query。谁能帮帮我?

 $query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in' => array( $product->get_id()),
    'post_status'    => 'publish',
    'post_type'      => 'product',
     
            'tax_query'      => array(
                'relation'      => 'OR',
                 array(
                     'taxonomy'     => 'product_cat',
                     'field'        => 'id',
                     'terms'        => $cats_array
                 ),
                array(
                    'taxonomy'     => 'product_tag',
                    'field'        => 'id',
                    'terms'        => $tags_array
                ) )
    );

要从您的自定义 WP 查询中删除缺货产品,您需要向旅游税查询添加一个额外的数组,如下所示:

$query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in'   => array( $product->get_id() ),
    'post_status'    => 'publish',
    'post_type'      => 'product',
    'tax_query'      => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => array('outofstock'),
            'operator' => 'NOT IN'
        ),
        array(
            'relation' => 'OR',
            array(
                'taxonomy'     => 'product_cat',
                'field'        => 'id',
                'terms'        => $cats_array
            ),
            array(
                'taxonomy'     => 'product_tag',
                'field'        => 'id',
                'terms'        => $tags_array
            )
        )
    ),
);

或者也可以这样使用元查询:

$query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in'   => array( $product->get_id() ),
    'post_status'    => 'publish',
    'post_type'      => 'product',
    'tax_query'      => array(
        'relation' => 'OR',
        array(
            'taxonomy'     => 'product_cat',
            'field'        => 'id',
            'terms'        => $cats_array
        ),
        array(
            'taxonomy'     => 'product_tag',
            'field'        => 'id',
            'terms'        => $tags_array
        )
    ),
    'meta_query'    => array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => '!='
    )
);

应该可以。

相关: