首页 文章

用于检索Woocommerce中产品分类的SQL查询

提问于
浏览
2

在Woocommerce中,我有大约8个不同类别的许多产品 . 当用户购买商品时,发送给他们的电子邮件按照他们将商品添加到购物车的顺序列出产品,这看起来非常混乱 . 我想按产品类别订购产品,并在每个类别中按字母顺序列出产品 . 我认为这种“双重排序”功能最好通过修改在发送电子邮件之前调用的SQL查询来实现,如下所示:

$line_items = $wpdb->get_results( $wpdb->prepare( "
SELECT      order_item_id, order_item_name, order_item_type
FROM        {$wpdb->prefix}woocommerce_order_items
WHERE       order_id = %d
AND         order_item_type IN ( '" . implode( "','", $type ) . "' )
ORDER BY    order_item_id
//Would like this to be ORDER BY 'product category', 'product name' ASC//
", $this->id ) );

我无法弄清楚的是如何在此查询中检索产品类别 . 我知道它需要一个JOIN,但对于我的生活,我无法追踪数据库表中的关键关系 .

更新:一个woocommerce产品存储为具有常规WordPress分类的帖子,所以如果有人知道如何检索WordPress中的帖子类别,我认为这将有效 .

1 回答

  • 1

    您可以使用以下代码,但这仅在您的每个产品只属于一个类别时才有用

    $line_items = $wpdb->get_results( $wpdb->prepare( "
    SELECT      DISTINCT woi.order_item_id, woi.order_item_name, woi.order_item_type, woim.meta_value AS product_id, t.name AS product_category
    FROM        {$wpdb->prefix}woocommerce_order_items AS woi
    LEFT JOIN   {$wpdb->prefix}woocommerce_order_itemmeta AS woim 
    ON ( woi.order_item_id = woim.order_item_id AND woim.meta_key LIKE '_product_id' )
    LEFT JOIN   {$wpdb->prefix}term_relationships AS tr
    ON ( tr.object_id = woim.meta_value )
    LEFT JOIN   {$wpdb->prefix}term_taxonomy AS tt ON ( tt.term_taxonomy_id = tr.term_taxonomy_id )
    LEFT JOIN   {$wpdb->prefix}terms AS t ON ( t.term_id = tt.term_id )
    WHERE       woi.order_id = %d
    AND         woi.order_item_type IN ( '" . implode( "','", $type ) . "' )
    AND         tt.taxonomy LIKE 'product_cat'
    ORDER BY    product_category, woi.order_item_name
    ", $this->id ) );
    

    希望这会有用 .

相关问题