我在为WooCommerce制作自定义报告时做了这样的事情,因为数据在表格中,而不是WordPress的一部分。我也给你提建议,除了研究,我不能说出你在这里想要完成的一切WP_Query 很多,因为大多数WordPress查询都可以用它来完成,只有当无法完成时,才应该考虑使用$wpdb custom query 就像我在这里介绍的一样。
//Need to call the $wpdb global
global $woocommerce, $wpdb;
// Write your own custom query using $wpdb->prefix
$sql = "
#<!--All Campaign Products and Quantity-->
SELECT orders.order_item_id, meta_product.meta_value as product, meta_qty.meta_value as qty, pm.meta_value AS donation
FROM {$wpdb->prefix}woocommerce_order_items AS orders
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS meta_product ON (orders.order_item_id = meta_product.order_item_id AND meta_product.meta_key=\'_product_id\')
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS meta_qty ON (orders.order_item_id = meta_qty.order_item_id AND meta_qty.meta_key=\'_qty\')
LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (meta_product.meta_value = pm.post_id AND pm.meta_key = \'donation_amount\')
WHERE orders.order_item_id IN (".$this->sql_items_from_campaign($cid).")";
// Results can be parsed as OBJECT, OBJECT_K, ARRAY_A, ARRAY_N
$result = $wpdb->get_results($sql, OBJECT);
// See your results printed out (optional)
print_r($result);
// Simple PHP loop
$donations = 0;
foreach ($result as $k => $v) {
$donations = $donations + ($v->donation * $v->qty);
}
==== UPDATE BASED ON QUESTION CHANGES =====
请注意,您应该能够回显$sql,然后将结果复制并传递到phpmyadmin中的编辑sql部分,这对于调试您实际上得到了正确的结果非常有用。还请记住使用以下内容
{wpdb->prefix}
这样,当使用不同的表前缀时,代码不会中断。
因为您可以在$results
数组我假设您得到了预期的响应。从那里,您需要使用一个简单的PHP循环来获取所需的数据。(this will differ based on if you selected OBJECT, OBJECT_K, ARRAY_A, ARRAY_N for the $results)
// For OBJECT
foreach ($result as $key => $value) {
echo $value->vehicle_id;
echo $value->manufacturer;
echo $value->series
echo $value->class;
}