猿问

使用数组过滤 Woocommerce 中的随机产品

作为 PHP 中的菜鸟,我正在尝试使用数组过滤掉 Woocommerce 中的产品。我设法只按类别过滤它们。


我还想过滤掉那些缺货和草稿的(如果可能的话,按数组)。


还有一个问题,我如何添加'product_cat'多个类别?例如,当我想过滤连帽衫和衬衫时?


对于库存产品,我尝试了以下代码,但不起作用:


'meta_value' => array(

        array(

            'key' => 'get_stock_status',

            'value' => 'outofstock',

            'compare' => '!='

        )

    )

不确定,如何检查它们是否是草稿。


这是我的代码:


<ul class="products">

 <?php

 $args = array(

 'post_type' => 'product',

 'orderby' => 'rand',

 'posts_per_page' => 1,

 'product_cat' => 'hoodies'


 );

 $loop = new WP_Query( $args );

 if ( $loop->have_posts() ) {

 while ( $loop->have_posts() ) : $loop->the_post();

 woocommerce_get_template_part( 'content', 'product' );

 endwhile;

 } 


 wp_reset_postdata();

 ?>

</ul>


森林海
浏览 191回答 1
1回答

弑天下

您可以通过传递参数来检查产品是否有库存 meta_query'meta_query' => array(&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'key' => '_stock_status',&nbsp; &nbsp; &nbsp; &nbsp; 'value' => 'instock'&nbsp; &nbsp; ))检查多个类别,category__and您需要传递一组类别 ID'category__and' => array(1,2) // select categories with array of IDs并检查已发布的帖子/产品,您需要传递publish给post_status:'post_status' => 'publish' // select products that are published放在一起可能看起来像这样(注意:未测试)&nbsp;$args = array(&nbsp; &nbsp; &nbsp;'post_type' => 'product',&nbsp; &nbsp; &nbsp; 'orderby' => 'rand',&nbsp; &nbsp; &nbsp; 'posts_per_page' => 1,&nbsp; &nbsp; &nbsp; 'category__and' => array(1,2), // replace these with your cat IDs&nbsp; &nbsp; &nbsp; 'post_status' => 'publish',&nbsp; &nbsp; &nbsp; 'meta_query' => array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'key' => '_stock_status',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'value' => 'instock'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)&nbsp; &nbsp; &nbsp; &nbsp;)&nbsp; );&nbsp; $loop = new WP_Query( $args );&nbsp; if ( $loop->have_posts() ) {&nbsp; &nbsp; &nbsp; &nbsp;while ( $loop->have_posts() ) : $loop->the_post();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; woocommerce_get_template_part( 'content', 'product' );&nbsp; &nbsp; &nbsp; &nbsp;endwhile;&nbsp; }&nbsp;&nbsp; wp_reset_postdata();
随时随地看视频慕课网APP

相关分类

Python
我要回答