在Woocommerce中获取所有具有“instock”库存状态的父产品

时间:2017-12-29 13:07:47

标签: php sql wordpress woocommerce product

在WooCommerce中,我有以下SQL查询来选择父产品。我想只选择“库存”产品。

这是我的实际SQL查询:

$query=$db->query("select * from wp_posts 
  where post_parent='0' and post_type='product'  and post_status='publish' 
  group by ID 
  limit 10");

如何只选择“有库存”的母产品(但不是全部)

1 个答案:

答案 0 :(得分:1)

只获取库存状态为“instock”的父产品的正确方法: :

global $wpdb;

// The SQL query
$results = $wpdb->get_results( "
    SELECT p.*, pm.meta_value as stock_status
    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 p.post_parent = '0'
    AND pm.meta_key LIKE '_stock_status'
    AND pm.meta_value LIKE 'instock' 
    GROUP BY p.ID
" );

// Testing output (objects array)
echo '<pre>'; print_r($results); echo '</pre>';

经过测试和工作。

仅获取产品ID:

global $wpdb;

// The SQL query
$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 p.post_parent = '0'
    AND pm.meta_key LIKE '_stock_status'
    AND pm.meta_value LIKE 'instock' 
" );

// Testing output (array of IDs)
echo '<pre>'; print_r($results); echo '</pre>';