mysql - woocomerce如何获取类别中的产品

时间:2017-11-15 12:15:55

标签: php mysql wordpress woocommerce

我正在撰写网络服务,我需要获取某个类别中的所有产品,到目前为止我已写过:

   SELECT *,ID, `post_date` ,  `post_title` ,  `post_content` ,  `guid` FROM  `wp_posts` as post

INNER JOIN wp_term_relationships rs ON rs.object_id = post.ID 
INNER JOIN wp_terms t ON t.term_id = rs.term_taxonomy_id 


WHERE  `post_type` =  'product'  
AND  `post_status` =  'publish'     
AND rs.term_taxonomy_id =909

代码返回3个项目,但问题是,我的网站和此网站中显示的所有这20个产品中约有20个此类产品。

这段代码有什么问题?我如何才能获得所有类别的产品? 顺便说一句,如果我可以使用woocomrce api,我也会使用它。

1 个答案:

答案 0 :(得分:2)

您可以使用以下自定义查询

获取与特定类别相关的所有产品
 //your custom category id   
 $cat_ids          =   123;
 $conn          =   new mysqli($servername, $username, $password,$database);

 $get_pro_by_cat   =   'SELECT ID, `post_title` FROM  `wp_posts` as post 
                       INNER JOIN wp_term_relationships rs ON rs.object_id = 
                       post.ID WHERE  `post_type` =  "product" AND `post_status` 
                       =  "publish" AND rs.term_taxonomy_id  =' .$cat_ids.' 
                       ORDER BY post_title';

$avail_products = $conn->query($get_pro_by_cat);

注意:在上面的查询中用 wp _ 表格前缀替换您的表格前缀 的 WP _posts。

您可以在此网址上看到演示:http://cadjewelrygallery.com/。 我希望它会对你有所帮助。