以下函数将为您提供一个数组,其中包含从每个自定义元字段“Brand”值的所有产品变体中计算出的库存量,使用WPDB
类(SQL查询):
global $wpdb;
$results = $wpdb->get_results( "
SELECT pm.meta_value as brand, SUM(pm2.meta_value) as stock
FROM {$wpdb->prefix}postmeta pm
INNER JOIN {$wpdb->prefix}posts p
ON pm.post_id = p.post_parent
INNER JOIN {$wpdb->prefix}postmeta as pm2
ON p.ID = pm2.post_id
WHERE p.post_status = \'publish\'
AND p.post_type = \'product_variation\'
AND p.post_parent > 0
AND pm.meta_key = \'Brand\'
AND pm2.meta_key = \'_stock\'
AND pm2.meta_value != \'\'
AND pm2.meta_value != \'NULL\'
GROUP BY pm.meta_value
");
// Display (example)
echo \'<ul class="stock-by-brand">\';
foreach ($results as $result ) {
echo \'<li><strong>\' . $result->brand . \'</strong>: \' . $result->stock . \'</li>\';
}
echo \'<ul>\';
测试和工作