在 WooCommerce 中仅获取有关产品查询的特定数据

Get only specific data on a product query in WooCommerce

我正在尝试从数组中获取 WooCommerce 中的所有产品,稍后我将使用它与外部数据库同步。

在下面的代码中,我使用 wc_get_products() 函数 returns 每个产品的数据量非常大 (我大部分不需要):

$args = array(
'status' => 'publish',
'limit' => -1,
);
$wooExistingProducts = wc_get_products($args);

相反,我可以做些什么来只获取产品 ID、产品名称和产品价格?

对于每个产品,我都希望有类似的东西:

[
{
id: 315892135,
name: Food for Hamster
price: 5$
}
{
id: 129414,
name: ....
price:...
}
....
]

我尝试使用 WP_Query 代替,但没有提供更好的解决方案。

实际上是 wc_get_products() is 'return' => 'ids' to get only product IDS when using a WC_Product_Query 的唯一可用过滤器。

解决方案 是在 WordPress WPDB Class 中使用 直接 SQL 查询 因为它是 更轻最有效 的方式来获取产品查询中所需的数据。

在下面的查询中,我们必须排除变量产品,因为它们有多个价格(每个变量一个)

global $wpdb;

$products_query = $wpdb->get_results( "
    SELECT  p.ID AS id,
            p.post_title AS name,
            Max(CASE WHEN pm.meta_key = '_price' AND  p.ID = pm.post_id THEN pm.meta_value END) AS price
    FROM    {$wpdb->prefix}posts p
            INNER JOIN {$wpdb->prefix}postmeta pm
                ON p.ID = pm.post_id
    WHERE   p.post_type = 'product'
            AND p.post_status = 'publish'
            AND p.post_parent != 0
    GROUP BY p.ID
    ORDER BY p.ID ASC;
" );

// Testing raw output
echo '<pre>'; print_r( $products_query ); echo '</pre>'; 

包括产品变化 (选项)

如果您想包括可变产品的产品变体,您应该替换此行:

WHERE   p.post_type = 'product'

作者:

WHERE   p.post_type IN ('product','product_varation')

I don't recommend you to use wc_get_products() or get_posts() (WP_Query) in your case:

  • as you will get also variable products (that have multiple prices depending on its variations)
  • as it's much more heavier (even if you query only 'ids' field, to get only product Ids), because you will have to set the data for each product, making multiple database queries.