如何将两个元值传递给WP_Query

时间:2016-10-13 08:22:55

标签: wordpress advanced-custom-fields

我的WP_Query问题。所以我有两个选择框使用ACF创建一个用于Country,一个用于扇区。当我选择国家并将部门留空时,我会获得所选国家/地区的所有帖子,并且对于该行业来说是明智的。我需要做的是进一步过滤它,如果两者都被选中而不只是一个我从该国家和部门获得所有帖子。我的支持低于任何帮助表示赞赏。

$field_key_country = "field_57b4439b5e371";
$field_country = get_field_object($field_key_country);
$country_sector = isset($_POST['country_select'])? sanitize_text_field($_POST['country_select']) : false;

$sector_key = "field_57e15152d896d";
$sector_field = get_field_object($sector_key);
$sector = isset($_POST['sector_select'])? sanitize_text_field($_POST['sector_select']) : false;

$args = array(
   'post_type' => 'distributer_search', 
   'posts_per_page' => -1,
   'meta_query' => array(
       'relation'       => 'OR',
        array(
           'key'        => 'dis_country',
           'value'      => $country_sector,
        ),
        array(
            'key'       => 'dis_sector',
            'value'     => $sector,
        )
    )
);

2 个答案:

答案 0 :(得分:0)

请尝试使用关系AND&的代码比较运算符。 另请查看https://codex.wordpress.org/Class_Reference/WP_Query

上的WP_Query课程

<?php
	$country_sector = isset($_POST['country_select'])? sanitize_text_field($_POST['country_select']) : '';
	$sector = isset($_POST['sector_select'])? sanitize_text_field($_POST['sector_select']) : '';
	$args = array(
		'post_type' => 'distributer_search', 
		'posts_per_page' => -1,
		'meta_query' => array(
			'relation'       => 'AND',
			array(
				'key'        => 'dis_country',
				'value'      => $country_sector,
				'compare' 		=> '=',
			),
			array(
				'key'       => 'dis_sector',
				'value'     => $sector,
				'compare' 		=> '=',
			)
		)
	);
?>

 'distributer_search',         'posts_per_page'=&gt; -1,         'meta_query'=&gt;阵列(             'relation'=&gt; '和',             阵列(                 'key'=&gt; 'dis_country',                 'value'=&gt; $ country_sector,                 'compare'=&gt; '=',             )             阵列(                 'key'=&gt; 'dis_sector',                 'value'=&gt; $部门,                 'compare'=&gt; '=',             )         )     ); ?&GT;

答案 1 :(得分:0)

可能对你有帮助 -

$field_key_country = "field_57b4439b5e371";
$field_country = get_field_object($field_key_country);
$country_sector = isset($_POST['country_select'])? sanitize_text_field($_POST['country_select']) : false;

$sector_key = "field_57e15152d896d";
$sector_field = get_field_object($sector_key);
$sector = isset($_POST['sector_select'])? sanitize_text_field($_POST['sector_select']) : false;

$args = array(
   'post_type' => 'distributer_search', 
   'posts_per_page' => -1
);
if($country_sector){
    $args['meta_query'][] = array(
        'key'        => 'dis_country',
        'value'      => $country_sector
    );
}
if($sector){
    $args['meta_query'][] = array(
        'key'       => 'dis_sector',
        'value'     => $sector
    );
}