Woocommerce,使用wp查询按类别获取产品

时间:2017-12-05 09:19:15

标签: php wordpress woocommerce

我尝试了很多方法,但我无法显示带有类别名称或ID的产品

                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );

4 个答案:

答案 0 :(得分:1)

尝试tax_query

$args = array(
   'post_type'             => 'product',
   'post_status'           => 'publish',
   'ignore_sticky_posts'   => 1,
   'posts_per_page'        => '12',
   'tax_query'             => array(
        array(
            'taxonomy'  => 'product_category',
            'field'     => 'term_id',
            'terms'     => array('40'),
            'operator'  => 'IN',
        )
   )
);

$loop = new WP_Query( $args );

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

答案 1 :(得分:1)

试试这个例子,

所以给定一个ID为26的类别,以下代码将返回它的产品(WooCommerce 3 +):

 $args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => '12',
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'field' => 'term_id', //This is optional, as it defaults to 'term_id'
            'terms'         => 26,
            'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
        ),
        array(
            'taxonomy'      => 'product_visibility',
            'field'         => 'slug',
            'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
            'operator'      => 'NOT IN'
        )
    )
);
$products = new WP_Query($args);
var_dump($products);

答案 2 :(得分:0)

试试这个,

<?php
  $args     = array( 'post_type' => 'product', 'post_status' => 'publish','category' => 34, 'ignore_sticky_posts' => 1, 'posts_per_page' => '12',);
  $products = get_posts( $args ); 
?>

希望这会对你有所帮助。更多info.

答案 3 :(得分:-1)

我建议使用&gt;&gt; wc_get_product_terms($ vars-&gt; ID,&#39; pa_brand_category&#39;)

请检查此屏幕截图&gt;&gt; http://prntscr.com/hjawu5

相关问题