按类别ID获取产品

时间:2013-11-06 17:14:31

标签: wordpress woocommerce

我正在为woocommerce写一个定价表插件。用户使用id为woocommerce产品类别插入短代码,在更新页面后,用户可以看到包含产品名称和价格列表的表格。
如何获得具有其类别ID的产品列表?!
在下面的代码中 $ pid 是用户在短代码中输入的内容,'object_id'是wp_posts表中每个产品的ID。

<?php
    $products = $wpdb->get_results("SELECT object_id FROM {$wpdb->term_relationships}
                                      WHERE term_taxonomy_id = " . $pid);
    if(!empty($products))
    {
        foreach($products as $product)
        {
            //the code
        }
    }
?>  

提前致谢。

3 个答案:

答案 0 :(得分:2)

 $args = array(
    'post_status' => 'publish',
    'tax_query' => array(
         'taxonomy' => 'product_cat',
         'field'    => 'term_id',
         'terms'     =>  '[ category id here ]', // When you have more term_id's seperate them by komma.
         'operator'  => 'IN'
         )
    );
    $the_query = wp_query($args);

未经测试但应该正常工作

答案 1 :(得分:1)

通过使用 get_posts wordpress函数

按类别获取所有WooCommerce 产品详细信息

$all_products = get_posts( array(
    'post_type' => 'product',
    'numberposts' => -1,
    'post_status' => 'publish',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'your_product_category', /*category name*/
            'operator' => 'IN',
            )
        ),
    ));
    echo var_dump($all_products);

按类别获取所有WooCommerce 产品ID

$all_ids = get_posts( array(
  'post_type' => 'product',
  'numberposts' => -1,
  'post_status' => 'publish',
  'fields' => 'ids',
  'tax_query' => array(
      array(
          'taxonomy' => 'product_cat',
          'field' => 'slug',
          'terms' => 'your_product_category', /*category name*/
          'operator' => 'IN',
          )
       ),
   ));
   foreach ( $all_ids as $id ) {
       echo $id;
   }

经过测试,可以正常工作。

答案 2 :(得分:0)

上面的(可接受的)答案对我来说不起作用(结果应该超出预期)(版本4.9.8)

 'tax_query' => array(
     array(
        'taxonomy' => 'product_cat',
        'field'    => 'term_id',
        'terms'     =>  [$request['id']],
        'operator'  => 'IN'
      )
  )

以上工作。我不是真正的Wordpress人,但我想这是一个版本问题...

相关问题