WPDB SQL查询从类别中选择

时间:2019-09-26 作者:Ru Leva

我编写SQL查询以获取状态为“instock”的项目ID,但不知道如何添加以仅从指定的产品类别中进行选择。

我的代码:

$results = $wpdb->get_col( "
    SELECT p.ID
    FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
    WHERE p.post_type LIKE \'product\'
    AND p.post_status LIKE \'publish\'
    AND pm.meta_key LIKE \'_stock_status\'
    AND pm.meta_value LIKE \'instock\' 
" );

2 个回复
SO网友:Milan Hirpara

如果您正在按指定类别查找产品。请查找以下代码:

$results = $wpdb->get_col( "
    SELECT p.ID
    FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
    LEFT JOIN {$wpdb->prefix}term_relationships ON ({$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id) 
    WHERE p.post_type LIKE \'product\'
    AND p.post_status LIKE \'publish\'
    AND pm.meta_key LIKE \'_stock_status\'
    AND pm.meta_value LIKE \'instock\' 
    AND {$wpdb->prefix}term_relationships.term_taxonomy_id IN ( \'cat 1\', \'cat 2\', \'cat 3\' ) 
" );
Note : 您需要将“cat 1”、“cat 2”和“cat 3”替换为您的类别。

SO网友:Hristo Hristov

如果您必须使用$wpdb:

$results = $wpdb->get_col( 
  $wpdb->prepare( "
    SELECT p.ID
    FROM $wpdb->posts as p
    INNER JOIN $wpdb->postmeta as pm ON p.ID = pm.post_id
    INNER JOIN $wpdb->term_relationships as tr ON p.ID = tr.object_id
    WHERE p.post_type = \'product\'
    AND p.post_status = \'publish\'
    AND pm.meta_key = \'_stock_status\'
    AND pm.meta_value = \'instock\'
    AND tr.term_taxonomy_id = %d
  ", $cat_id)
);
如果要按类别名称而不是ID进行选择,则必须加入另一个表:

$results = $wpdb->get_col( 
  $wpdb->prepare( "
    SELECT p.ID
    FROM $wpdb->posts as p
    INNER JOIN $wpdb->postmeta as pm ON p.ID = pm.post_id
    INNER JOIN $wpdb->term_relationships as tr ON tr.object_id = p.ID
    INNER JOIN $wpdb->terms as t ON t.term_id = tr.object_id
    WHERE p.post_type = \'product\'
    AND p.post_status = \'publish\'
    AND pm.meta_key = \'_stock_status\'
    AND pm.meta_value = \'instock\'
    AND t.name %LIKE% %s
  ", $wpdb->esc_like($cat_name) )
);

However, the preferred method for querying products, is this:

$products = wc_get_products( array(
  \'category\' => array( \'shirts\' ),
  \'stock_status\' => \'instock\',
  \'status\' => \'publish\',
));

wc_get_products and WC_Product_Query