我正在 wordpress 中进行自定义搜索,我想通过从自定义元键中搜索来找到我的自定义类型文章。
此代码按自定义类型过滤帖子,但按自定义元过滤所有帖子,未显示任何结果!
function filtri_di_ricerca( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
if (is_home())
{
$query->set('post_type', 'post_annunci');
$query->set('posts_per_page', 1000);
$meta_query = array();
// Only check these form fields
$fields = array( 'annuncio_contratto', 'annuncio_categorie', 'annuncio_tipologia', 'annuncio_citta', 'annuncio_prezzo');
foreach( $fields as $field ) {
if( $_GET[$field] != '' ) {
// We have something to match, otherwise ignore the field...
$meta_query[] = array(
'key' => $field,
'value' => $_GET[$field],
'compare' => '='
);
}
}
$meta_query['relation'] = 'AND';
$query->set('meta_query',$meta_query);
}
return;
}
add_action( 'pre_get_posts', 'filtri_di_ricerca');
搜索地址为:
http://example.com/?annuncio_contratto=Vendita&annuncio_categorie=Residenziale&annuncio_tipologia=Appartamento&annuncio_citta=NewYork
调试:
echo "<pre>"; print_r($wp_query->query_vars); echo "</pre>";
结果:
Array
(
[error] =>
[m] => 0
[p] => 0
[post_parent] =>
[subpost] =>
[subpost_id] =>
[attachment] =>
[attachment_id] => 0
[name] =>
[static] =>
[pagename] =>
[page_id] => 0
[second] =>
[minute] =>
[hour] =>
[day] => 0
[monthnum] => 0
[year] => 0
[w] => 0
[category_name] =>
[tag] =>
[cat] =>
[tag_id] =>
[author_name] =>
[feed] =>
[tb] =>
[paged] => 0
[comments_popup] =>
[meta_key] =>
[meta_value] =>
[preview] =>
[s] =>
[sentence] =>
[fields] =>
[menu_order] =>
[category__in] => Array
(
)
[category__not_in] => Array
(
)
[category__and] => Array
(
)
[post__in] => Array
(
)
[post__not_in] => Array
(
)
[tag__in] => Array
(
)
[tag__not_in] => Array
(
)
[tag__and] => Array
(
)
[tag_slug__in] => Array
(
)
[tag_slug__and] => Array
(
)
[post_type] => post_annunci
[posts_per_page] => 1000
[meta_query] => Array
(
[0] => Array
(
[key] => annuncio_contratto
[value] => Vendita
[compare] => =
)
[1] => Array
(
[key] => annuncio_categorie
[value] => Residenziale
[compare] => =
)
[2] => Array
(
[key] => annuncio_tipologia
[value] => Appartamento
[compare] => =
)
[3] => Array
(
[key] => annuncio_citta
[value] => Pesaro
[compare] => =
)
[relation] => AND
)
[ignore_sticky_posts] =>
[suppress_filters] =>
[cache_results] => 1
[update_post_term_cache] => 1
[update_post_meta_cache] => 1
[nopaging] =>
[comments_per_page] => 50
[no_found_rows] =>
[order] => DESC
)