我想在 woocommerce 的两个不同列中获取类别和类别的产品列表

I want to get product list with category and category listed as in two different columns in woocommerce

我想在 woocommerce 的结果中将父类别和子类别分开的产品列表

这段代码我试过了

SELECT
p.ID,
 p.post_title,
 `post_content`,
`post_excerpt`,
t.name AS product_category,
t.term_id AS product_id,
t.slug AS product_slug,
tt.term_taxonomy_id AS tt_term_taxonomia,
tr.term_taxonomy_id AS tr_term_taxonomia,
MAX(CASE WHEN pm1.meta_key = '_price' then pm1.meta_value ELSE NULL END) as price,
MAX(CASE WHEN pm1.meta_key = '_regular_price' then pm1.meta_value ELSE NULL END) as 
regular_price,
MAX(CASE WHEN pm1.meta_key = '_sale_price' then pm1.meta_value ELSE NULL END) as sale_price,
MAX(CASE WHEN pm1.meta_key = '_sku' then pm1.meta_value ELSE NULL END) as sku
FROM wp_posts p
LEFT JOIN wp_postmeta pm1 ON pm1.post_id = p.ID
LEFT JOIN wp_term_relationships AS tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id = 
tr.term_taxonomy_id
JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE p.post_type in('product', 'product_variation') AND p.post_status = 'publish' AND 
p.post_content <> ''
GROUP BY p.ID,p.post_title

任何想法,提前致谢

如果您想以数组格式获取带有 parent_categorysub_category 的产品列表,那么您可以使用 WordPress WP_Query。试试下面的代码片段。

<?php
    // fetch all products from woocommerce
    $args = array('post_type' => 'product', 'posts_per_page' => -1); 
    $loop = new WP_Query($args);

    $product_list_array = []; // result array with product_id,parent_category and sub_category

    while ($loop->have_posts()) : $loop->the_post();
        global $product;
        $product_id = $product->get_id();
        $result = []; $parent_cats = []; $sub_cats = []; 
        $result['product_id'] = $product_id;
        $categories = get_the_terms($product_id, 'product_cat'); // get category list of a product
        foreach ($categories as $category) {
            // check if it is a parent or child
            if ($category->parent == 0) {
                $parent_cats[] = $category->name;
            } else {
                $parent_cat = get_term_by('id', $category->parent, 'product_cat'); // to get parent category name 
                $sub_cats[] = $category->name;
                $parent_cats[] = $parent_cat->name;
            }
        }
    
        // if multiple category exist then join them to a string
        $result['parent_category'] = implode(" | ", array_unique($parent_cats));
        $result['sub_category'] = implode(" | ", array_unique($sub_cats));
        $product_list_array[] = $result;
    endwhile;
?>

$product_list_array 应包含 product_id、parent_category 和 sub_category。