Jor*_*508 1 php mysql wordpress posts
我正在尝试在产品列表中应用过滤器。用户将使用前端的选择框,然后单击按钮以过滤产品。
每个产品都是它自己的帖子,因此我使用WP_Query来获取帖子。例如,我想要所有颜色为“红色”,材料为“塑料”和品牌为“ 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' => '='
)
)
));
Run Code Online (Sandbox Code Playgroud)
如果设置了每个值,这将很好地工作。但是,如果仅使用一个选择框,则其他两个值将为空,并且查询将不返回任何帖子。有什么办法说“如果设置了此值,则仅在元查询中使用此数组”?
您可以检查变量的定义并添加其他过滤(如果存在)
$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);
Run Code Online (Sandbox Code Playgroud)