我无法按类别ID提取WooCommerce产品 [英] I can't fetch WooCommerce products by category id
本文介绍了我无法按类别ID提取WooCommerce产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试通过以下方式按类别ID提取产品:
I am trying to fetch products by category ID this way:
<?php
$args = array(
'posts_per_page' => 20,
'taxonomy' => 'product_cat',
'post_type' => 'product',
'post_status' => 'publish',
'cat' => $cat_id
);
$query = new WP_Query($args);
$posts = get_posts($args);
var_dump($posts);
?>
$ cat_id
变量包含正确的类别ID。我已经检查过了产品被添加到正确的类别。
The $cat_id
variable contains the correct category ID. I've checked it. Products are added to correct categories.
问题是,每当我 var_dump
$ posts
变量,我得到一个空数组。从参数中删除猫
关键字后,我可以毫无问题地获取所有类别的产品。唯一的问题是'cat'
关键字。
The problem is, whenever I var_dump
the $posts
variable I get an empty array. As soon as I remove the 'cat'
keyword from the arguments I can fetch products from all categories with no problems. The only problem is the 'cat'
keyword.
我做错了吗?
推荐答案
您可以尝试以下方法:
$args = array(
'posts_per_page' => 20,
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' = array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'term' => $cat_id
)
);
$query = new WP_Query($args);
var_dump($query);
我还没有测试过,但是应该可以。
I haven't test it, but it should work.
这篇关于我无法按类别ID提取WooCommerce产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文