dongwei1263 2019-07-13 09:35
浏览 76
已采纳

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

As a noob in PHP, I'm trying to filter out products in Woocommerce using array. I managed to only filter them by category.

I also would like to filter out ones, that are out of stock and drafts (by array, if possible).

And one more question, how do I add in 'product_cat' more than one category? When I want to filter hoodies and shirts for example?

For the in stock product I have tried following code, which doesn't work:

'meta_value' => array(
        array(
            'key' => 'get_stock_status',
            'value' => 'outofstock',
            'compare' => '!='
        )
    )

Not sure, how to check if they are drafts or not.

This is my code:

<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>
  • 写回答

1条回答 默认 最新

  • dtzk85937 2019-07-13 11:44
    关注

    You can check if products are in stock by passing arguments to meta_query

    'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        )
    )
    

    Checking for multiple categories with category__and you'd need to pass an array of category IDs

    'category__and' => array(1,2) // select categories with array of IDs
    

    And to check for posts/products that are published you need to pass publish to post_status:

    'post_status' => 'publish' // select products that are published
    

    Together it might look something like this (Note: Not tested)

     $args = array(
         'post_type' => 'product',
          'orderby' => 'rand',
          'posts_per_page' => 1,
          'category__and' => array(1,2), // replace these with your cat IDs
          'post_status' => 'publish',
          'meta_query' => array(
               array(
                   'key' => '_stock_status',
                   'value' => 'instock'
               )
           )
      );
    
      $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable