在 Woocommerce 中使用 SQL 从特定产品属性值获取产品 ID

Get product ids from specific product attributes values using SQL in Woocommerce

我正在尝试获取产品属性 pa_color = 'Black'pa_waterproof = 'Yes' 的产品 ID。但是我还没有成功

这是我的代码:

global $wpdb;

$product_id = $wpdb->get_results( "
    SELECT post_id 
    FROM $wpdb->postmeta 
    WHERE meta_key='pa_color' 
    AND meta_value='Black' 
    AND meta_key='pa_waterproof' 
    AND meta_value='Yes' 
" );

感谢任何帮助

更新 (与您的评论相关)

您可能正在尝试获取 可变产品 ID ,这不是一回事。

然后您可以使用普通产品属性分类法术语名称(甚至术语 ID 或术语别名).

在这种情况下,请尝试以下操作:

global $wpdb;

$results = $wpdb->get_col( "
    SELECT p.ID
    FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}term_relationships as tr ON p.ID = tr.object_id
    INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    INNER JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
    INNER JOIN {$wpdb->prefix}term_relationships as tr2 ON p.ID = tr2.object_id
    INNER JOIN {$wpdb->prefix}term_taxonomy as tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id
    INNER JOIN {$wpdb->prefix}terms as t2 ON tt2.term_id = t2.term_id
    WHERE p.post_type LIKE 'product'
    AND p.post_status LIKE 'publish'
    AND tt.taxonomy LIKE 'pa_color'
    AND t.name = 'Black'
    AND tt2.taxonomy LIKE 'pa_waterproof'
    AND t2.name = 'Yes'
");

// Raw output
echo '<pre>'; print_r($results); echo '</pre>';

经过测试并有效


第一个回答。

在 Woocommerce

中使用 SQL 从特定产品属性值获取产品变体 ID

在数据库中,post_meta table 中产品变体的产品属性注册术语是术语段(不是术语名称),所有产品属性 meta_key 都以 attribute_pa_ 而不是 pa_

所以它将是 attribute_pa_color = 'black'attribute_pa_waterproof = 'yes'

您还需要在 wp_posts table 上针对 product_variation post 类型 进行 SQL 查询加入2次wp_postmetatable查询每个商品属性

所以尝试:

global $wpdb;

$variation_id = $wpdb->get_var( "
    SELECT p.ID FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
    INNER JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
    WHERE p.post_type LIKE 'product_variation'
    AND p.post_status LIKE 'publish'
    AND pm.meta_key LIKE 'attribute_pa_color'
    AND pm.meta_value = 'black'
    AND pm2.meta_key LIKE 'attribute_pa_waterproof'
    AND pm2.meta_value = 'yes'
");

// Output
echo $variation_id . '<br>';

经过测试并有效