自定义查询获取产品

oknrviil  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(296)

这是基于wordpress和woocommerce以及处理post和post\元表
我必须得到所有的产品id,它有一个meta\u key=“\u shop”和meta\u value=“yes”
典型情况:
如果元键和元值与父产品匹配,那么它的所有变化也必须包括在内。
如果meta键和meta值没有与父级进行匹配,但其变体有meta键和meta值匹配,则只返回变体。

Product(#18)(simple):           _shop = 'yes'
Product(#19)(variable):         _shop = 'yes' (Parent is Yes)
       Product(#20)(variation): _shop = 'yes'
       Product(#21)(variation): _shop = 'no'
       Product(#22)(variation): _shop = 'no'
Product(#23)(simple):           _shop = 'yes'
Product(#24)(variable):         _shop = 'no'  (parent is no)
       Product(#25)(variation): _shop = 'no'
       Product(#26)(variation): _shop = 'yes' (Only this variation)
       Product(#20)(variation): _shop = 'no'

我需要的ID:

18 #19 #20 #21 #22 #23 #26

hfyxw5xn

hfyxw5xn1#

select  productID from your_table
   where meta_key = "_shop" and meta_value = "yes"
dfty9e19

dfty9e192#

add_action('init',function(){
    global $wpdb;
    $ids = $wpdb->get_results("
                                SELECT p.ID as id 
                                From $wpdb->posts as p
                                LEFT JOIN $wpdb->postmeta as m
                                ON p.ID = m.post_id
                                WHERE m.meta_key = '_shop'
                                AND m.meta_value = 'yes'
                                AND p.post_type = 'product' OR p.post_type = 'product_variation'
                            ");
    if(!empty($ids)){
        foreach ($ids as $id) {
            echo $id->id;
        }
    }
});

相关问题