【问题标题】:Filtering random products in Woocommerce using array使用数组过滤 Woocommerce 中的随机产品
【发布时间】:2019-07-13 09:35:41
【问题描述】:

作为 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>

【问题讨论】:

    标签: php arrays wordpress woocommerce


    【解决方案1】:

    您可以通过将参数传递给meta_query来检查产品是否有库存

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

    使用 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
    

    它可能看起来像这样(注意:未测试

     $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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多