WordPress通过产品变体库存进行查询

时间:2019-06-12 作者:wplearner

我有WooCommerce变量产品和一个过滤器,该过滤器基于变量属性过滤产品。我有一个变量属性depth,它有一个数值(从1到20),过滤器工作正常。但我只想显示库存变化,另一方面,它显示所有产品,包括缺货选择的深度值(变化)。所以我想隐藏产品,将有选择的深度值,但没有股票。

我可以通过库存查询产品吗?

这是它现在的工作原理。

$args = array(
\'post_type\' => array(\'product\'),
        \'meta_query\' => array(
            array(
                \'key\' => \'_stock_status\',
                \'value\' => \'instock\',
                \'compare\' => \'=\',
            ),
        ),

        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'pa_depth\',
                \'field\' => \'slug\',
                \'terms\' => $wccaf_depth,
                \'operator\'  => $wccaf_depth ? \'IN\' : \'NOT IN\'
            )
        ),                  
);

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

(Note to other readers: The question author and I have already discussed via chat, so I\'m going straight to the code.)

我认为出于性能原因,您应该这样做:

// FIRST PART: Get the variations which are in stock.

$paged = max( 1, get_query_var( \'paged\' ) );
$wccaf_depth = array( \'19\', \'1\' ); // example
$args = array(
    \'post_type\'     => \'product_variation\',
    \'meta_query\'    => array(
        \'relation\' => \'AND\',
        array(
            \'key\'     => \'_stock_status\',
            \'value\'   => \'instock\',
            \'compare\' => \'=\',
        ),
        array(
            \'key\'     => \'attribute_pa_tread-depth\',
            \'value\'   => $wccaf_depth,
            \'compare\' => \'IN\',
        ),
    ),
    \'fields\'         => \'id=>parent\',
    \'paged\'          => $paged,
    \'posts_per_page\' => 1, // example
    \'groupby\'        => \'post_parent\', // *this is a custom query arg
);

$q = new WP_Query( $args );
$parent_ids = wp_list_pluck( $q->posts, \'post_parent\' );

// SECOND PART: Get the parent products. Here you don\'t need the above
// meta_query, but you can of course make other meta queries.

$args = array(
    \'post_type\' => \'product\',
    \'post__in\'  => $parent_ids,
);

$loop = new WP_Query( $args );
// Run your loop here.

// Paginate the first part.
echo paginate_links( array(
    \'total\'   => $q->max_num_pages,
    \'current\' => $paged,
    //...
) );
并确保将此筛选器添加到函数文件中:

add_filter( \'posts_groupby\', \'custom_posts_groupby\', 10, 2 );
function custom_posts_groupby( $groupby, $query ) {
    if ( \'post_parent\' === $query->get( \'groupby\' ) ) {
        global $wpdb;
        return "$wpdb->posts.post_parent";
    }
    return $groupby;
}
但是,如果这种方法(我们将第一部分分页)不适用于您,请告诉我。但实际上,您可以随时查看answer\'s revisions..

相关推荐