如果您必须使用$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