php - Woocommerce 获取产品

标签 php wordpress woocommerce

我使用以下代码从我的 WordPress 网站中的 WooCommerce 获取产品类别列表:

 <?php
  $taxonomy     = 'product_cat';
  $orderby      = 'name';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 0;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;
$args = array(
  'taxonomy'     => $taxonomy,
  'orderby'      => $orderby,
  'show_count'   => $show_count,
  'pad_counts'   => $pad_counts,
  'hierarchical' => $hierarchical,
  'title_li'     => $title,
  'hide_empty'   => $empty
);
?>
<?php $all_categories = get_categories( $args );

//print_r($all_categories);
foreach ($all_categories as $cat) {
    //print_r($cat);
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;

?>     

<?php       

        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?>


        <?php
        $args2 = array(
          'taxonomy'     => $taxonomy,
          'child_of'     => 0,
          'parent'       => $category_id,
          'orderby'      => $orderby,
          'show_count'   => $show_count,
          'pad_counts'   => $pad_counts,
          'hierarchical' => $hierarchical,
          'title_li'     => $title,
          'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }

        } ?>



    <?php }     
}
?>

这工作正常并返回产品类别列表。我现在一直在尝试获取特定类别的产品列表。

示例:获取 cat_id=34 的所有产品。

我知道产品存储为帖子,并且一直在尝试完成此操作但似乎做不到。

如何获取特定类别的产品列表?

最佳答案

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

这将列出所有产品缩略图和名称及其指向产品页面的链接。根据您的要求更改类别名称和 posts_per_page。

关于php - Woocommerce 获取产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21028830/

相关文章:

html - Woocommerce 在添加到购物车按钮后添加图片

php - 如何在 woocommerce 中以编程方式插入产品类型

javascript - 使用 DateTimePicker 获取日期名称并更改服务时间列表

php - 从同一用户的两个表中获取数据?

php - 为什么 PHP `__invoke` 在从对象属性触发时不起作用

php - 使用 JQuery 表单中的值来选择与表单值匹配的数据库项目

JQuery Wrap 不生效,因为被 CSS 阻止了

wordpress - 如何编写 Mod Rewrite 来排除 Shibboleth url?

jquery - 使用 jQuery 在输入字段中设置最低价格

php - 迷你卡中的自定​​义价格值仅在单个产品站点上是错误的