php - 在 Woocommerce 中显示特定产品类别的产品

标签 php wordpress woocommerce product custom-taxonomy

我的 WordPress 网站中有此代码,它显示我拥有的产品:

<?php
$params = array('posts_per_page' => 5, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>
<ul>
     <?php if ($wc_query->have_posts()) : ?>
     <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>
     <li>
          <h3>
               <a href="<?php the_permalink(); ?>">
               <?php the_title(); ?>
               </a>
          </h3>
          <?php the_post_thumbnail(); ?>
          <?php the_excerpt(); ?>
     </li>
     <?php endwhile; ?>
     <?php wp_reset_postdata(); ?>
     <?php else:  ?>
     <li>
          <?php _e( 'No Products' ); ?>
     </li>
     <?php endif; ?>
</ul>

它工作正常,但我想显示我选择的类别中的产品,我该怎么做?

最佳答案

尝试以下操作:

<?php

// Here set your product category SLUG (can be multiple coma separated)
$product_categories = array('clothing');

$wc_query = new WP_Query( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    'tax_query' => array( array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $product_categories,
        'operator' => 'IN',
    ) )
) );
?>
<ul>
     <?php if ($wc_query->have_posts()) : ?>
     <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>
     <li>
          <h3>
               <a href="<?php the_permalink(); ?>">
               <?php the_title(); ?>
               </a>
          </h3>
          <?php the_post_thumbnail(); ?>
          <?php the_excerpt(); ?>
     </li>
     <?php endwhile; ?>
     <?php wp_reset_postdata(); ?>
     <?php else:  ?>
     <li>
          <?php _e( 'No Products' ); ?>
     </li>
     <?php endif; ?>
</ul>

经过测试并有效。

关于php - 在 Woocommerce 中显示特定产品类别的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50802271/

相关文章:

javascript - 静态网站中的表格分页问题

php - 记录某人使用 PHP 查看页面的时间的最简单方法是什么?

wordpress - 自动同步 wordpress 帖子与 blogger.com blogspot

php - 如何在结账页面复制标题?

php - 在 Woocommerce 注册表中添加一个字段并在管理员中编辑用户

wordpress - Woocommerce - Cookie 未定义

php - 测量类里面函数之间的时间?

php - 使用 PHP 将多个 XML 提要解析为一个排序数组

保存/发布 wordpress 时 MySQL super CPU 峰值

javascript - Gravity Forms 未在 https 下加载,未定义 jQuery