简体   繁体   English

如何在 WooCommerce 中使用 SQL 查询特定类别中的 select 产品

[英]How to select products in specific categories using SQL query in WooCommerce

I used below code to select products from specific categories and works fine but I want to select products if include more than one category我将以下代码用于特定类别的 select 产品并且工作正常,但如果包含多个类别,我想使用 select 产品

SELECT post.ID, post.post_title FROM  `wp_posts` as post

INNER JOIN wp_term_relationships AS tr ON tr.object_id = post.ID 
WHERE
post.`post_type` IN ('product','product_variation') 
AND tr.term_taxonomy_id  IN(32,25)

I use IN(32,25) and it returns all products, how can I filter products just included in two categories?我使用IN(32,25)并返回所有产品,如何过滤仅包含在两个类别中的产品?

To query products that are in specific categories (eg categories with the ids of 32 and 35), you could use this:要查询特定类别中的产品(例如,ID 为 32 和 35 的类别),您可以使用以下命令:

SELECT wp_posts.* FROM wp_posts LEFT JOIN wp_term_relationships 
ON (wp_posts.ID = wp_term_relationships.object_id) 
WHERE 1=1 
AND 
( wp_term_relationships.term_taxonomy_id IN (32,35) ) 
AND 
wp_posts.post_type = 'product' 
AND 
(wp_posts.post_status = 'publish') 
GROUP BY 
wp_posts.ID 
ORDER BY 
wp_posts.post_date DESC

It's recommended to use global $wpdb and take advantage of建议使用global $wpdb并利用

  • $wpdb->prefix for your wordpress table "prefix", instead if hard coding "wp_" $wpdb->prefix您的 wordpress 表“前缀”的前缀,而不是硬编码“wp_”

and

  • $wpdb->prepare for security. $wpdb->prepare

Like this:像这样:

global $wpdb;

$query = $wpdb->prepare(
    "SELECT {$wpdb->prefix}posts.* FROM {$wpdb->prefix}posts LEFT JOIN {$wpdb->prefix}term_relationships 
    ON ({$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id) 
    WHERE 1=1 
    AND 
    ( {$wpdb->prefix}term_relationships.term_taxonomy_id IN (32,35) ) 
    AND 
    {$wpdb->prefix}posts.post_type = 'product' 
    AND 
    ({$wpdb->prefix}posts.post_status = 'publish') 
    GROUP BY 
    {$wpdb->prefix}posts.ID 
    ORDER BY 
    {$wpdb->prefix}posts.post_date DESC"
);

$sql_results = $wpdb->get_results($query, ARRAY_A);

For security reasons, avoid writing your own sql queries as much as possible.出于安全原因,请尽可能避免编写自己的sql queries

In order to query your database try to use:为了查询您的数据库,请尝试使用:

or或者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM