使用
我试图从DB获得具有值条件的自定义字段的产品。
自定义字段命名:"_filtered_product">.
我只想获得值= 1的产品
这是我写的SQL查询。
$view_low_filt_sql =
"LEFT JOIN $wpdb->postmeta manage ON (p.ID = manage.post_id AND manage.meta_key = '_manage_stock')
LEFT JOIN $wpdb->postmeta stock ON (p.ID = stock.post_id AND stock.meta_key = '_stock')
LEFT JOIN $wpdb->postmeta threshold ON (p.ID = threshold.post_id AND threshold.meta_key = '_low_inventory_number')
LEFT JOIN $wpdb->postmeta filtered ON (p.ID = filtered.post_id AND filtered.meta_key = '_filtered_product')
WHERE (p.post_type = 'product' OR p.post_type = 'product_variation')
AND (p.post_status = 'publish' OR p.post_status = 'private' OR p.post_status = 'draft')
AND manage.meta_value = 'yes'
AND threshold.meta_value IS NOT NULL
AND filtered.meta_value = '1'
AND IFNULL(CAST(stock.meta_value AS SIGNED),0) <= CAST(threshold.meta_value AS SIGNED)
";
不知道为什么要为这个简单的任务编写自己的sql query
,而可以使用wp_query
!
话虽如此,您可以使用以下代码片段获取具有特定元键和元值的所有产品:
global $wpdb;
$meta_key = '_filtered_product';
$meta_value = '1';
$sql_statement = "SELECT {$wpdb->prefix}posts.* FROM {$wpdb->prefix}posts INNER JOIN {$wpdb->prefix}postmeta ON ( {$wpdb->prefix}posts.ID = {$wpdb->prefix}postmeta.post_id ) WHERE 1=1 AND ( ( {$wpdb->prefix}postmeta.meta_key = '{$meta_key}' AND {$wpdb->prefix}postmeta.meta_value = '{$meta_value}' ) ) AND {$wpdb->prefix}posts.post_type = 'product' AND ({$wpdb->prefix}posts.post_status = 'publish' OR {$wpdb->prefix}posts.post_status = 'private') GROUP BY {$wpdb->prefix}posts.ID ORDER BY {$wpdb->prefix}posts.post_date DESC";
$sql = $wpdb->prepare($sql_statement);
$sql_results = $wpdb->get_results($sql, ARRAY_A);
if ($sql_results) {
foreach ($sql_results as $result) {
echo "<p>Product id: " . $result['ID'] . " and product title: " . $result['post_title'] . "<p>";
}
} else {
echo "Sorry can't find anything at the moment!";
}
wp_reset_postdata();
输出如下:
Product id: {the product id} and product title: {the product name that matches the query}
注意:
- 上面的查询将检索产品的所有数据。我仅以
ID
和title
为例。 - 如果你的
$meta_value
是字符串,那么你就都设置好了,这意味着我已经写了查询,假设你的元值是字符串。然而,如果它不是,那么使用这个{$meta_value}
而不是'{$meta_value}'
。 - 我使用了全局
$wpdb
,并利用了它的属性和方法。而不是硬编码你的数据库表前缀默认是wp_
,我使用{$wpdb->prefix}
。 - 我也使用
$wpdb->prepare
语句来保护sql语句。 - 此外,我使用
ARRAY_A
作为$wpdb->get_results
函数中的第二个参数,以获得数据作为关联数组! - 另外,请注意此查询是按日期降序排序的,这意味着将首先输出最近的产品!
使用wp_query
执行相同的查询:
$meta_key = '_filtered_product';
$meta_value = '1';
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => '=',
)
)
);
$woo_custom_query = new WP_Query($args);
if ($woo_custom_query->have_posts()) {
while ($woo_custom_query->have_posts()) {
$woo_custom_query->the_post();
the_title();
}
} else {
echo "Sorry can't find anything at the moment!";
}
wp_reset_postdata();
这个答案已经在woocommerce5.x+
上完全测试过了,效果很好!