我想要一个返回包含用户输入(即$ text)的CPT帖子的查询。
插入meta_key和meta_value效果很好但是将它放在meta_query数组中不会返回任何内容。我希望能够在多个自定义字段中进行搜索。这是我从头开始制作的一个主题,所以没有插件,而且functions.php文件非常小,所以我不认为这可能是一个冲突。
查询声明中的meta_key和meta_value的代码(工作):
$searchquery = new WP_Query(
array( 'post_type' => 'offre',
'meta_key' => 'offre_employeur',
'meta_value' => $text,
'meta_compare'=> 'LIKE' )
);
meta_value数组的代码(不工作):
$meta_query_args = array(
'relation' => 'OR',
array(
'key' => 'offre_employeur',
'value' => $text,
'compare' => 'LIKE'
), array(
'key' => 'offre_titre',
'value' => $text,
'compare' => 'LIKE'
)
);
$searchquery = new WP_Query(array('post_type' => 'offre'));
$searchquery->set('meta_query', $meta_query_args);
我尝试的第二种方式的代码,但仍然没有结果(不工作)
$args = array(
'post_type' => 'offre',
'posts_per_page' => -1,
's' => $text,
'meta_query' => array(
array(
'key' => 'offre_employeur',
'value' => $text,
'compare' => 'LIKE'
),
array(
'key' => 'offre_titre',
'value' => $text,
'compare' => 'LIKE'
)
)
);
$searchquery = new WP_Query($args);
提前谢谢您的时间。
根据这里的文档:https://codex.wordpress.org/Class_Reference/WP_Query
我想断言你想要向下滚动到标题为“Multiple Custom Field Handling:”的部分,该部分有这个例子,它最接近你的情况:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE',
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
),
);
$query = new WP_Query( $args );
哪个,按照你在问题中提供的内容,我会修改如下以获得你所追求的结果:
$args = array(
'post_type' => 'offre',
'posts_per_page' => -1,
// remove the "search" query, which restricts the results to those with titles / content that match the $text content
// 's' => $text,
'meta_query' => array(
// add the "relation" argument, default is AND, you need OR
'relation' => 'OR',
array(
'key' => 'offre_employeur',
'value' => $text,
'compare' => 'LIKE'
),
array(
'key' => 'offre_titre',
'value' => $text,
'compare' => 'LIKE'
)
)
);
$searchquery = new WP_Query($args);