gpt4 book ai didi

php - 如果存在,如何仅应用 (Wordpress) 元查询

转载 作者:行者123 更新时间:2023-11-29 04:16:38 25 4
gpt4 key购买 nike

我正在尝试在产品列表中应用过滤器。用户将使用前端的选择框并单击按钮来过滤产品。

每个产品都是它自己的帖子,所以我使用 WP_Query 来获取帖子。例如,我想要所有颜色为“红色”、 Material 为“塑料”且品牌为“Bikon”的产品。所以我用;

$color = "red";
$material = "plastic";
$brand = "Bikon";
$query = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => 6,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => $color,
'compare' => '='
),
array(
'key' => 'material',
'value' => $material,
'compare' => '='
),
array(
'key' => 'brand',
'value' => $brand,
'compare' => '='
)
)
));

如果每个值都已设置,这将正常工作。但如果只使用其中一个选择框,则其他两个值将为空,查询将不会返回任何帖子。有什么方法可以说“如果设置了此值,则仅在元查询中使用此数组”?

最佳答案

您可以检查变量的定义并添加额外的过滤(如果存在)

$query_args = array(
'post_type' => 'products',
'posts_per_page' => 6,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'product_check',
'compare' => 'EXISTS',
),
),
);

if(isset($color) && $color) {
$query_args['meta_query'][] = array('key' => 'color', 'value' => $color, 'compare' => '=');
}

if(isset($material ) && $material ) {
$query_args['meta_query'][] = array('key' => 'material ', 'value' => $material , 'compare' => '=');
}

if(isset($brand ) && $brand ) {
$query_args['meta_query'][] = array('key' => 'brand ', 'value' => $brand , 'compare' => '=');
}

$query = new WP_Query($query_args);

关于php - 如果存在,如何仅应用 (Wordpress) 元查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41911804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com