Video Tutorial The pre_get_posts action
In this chapter we will talk about the hook pre_get_posts
. This hook allows to alter a request before its execution and will in particular allow to alter the main WordPress request to add specific filters.
/ **
* @param WP_Query $ query
* /
function montheme_pre_get_posts ($ query) {
if (is_admin () ||! is_search () ||! $ query-> is_main_query ()) {
return;
}
if (get_query_var ('sponso') === '1') {
$ meta_query = $ query-> get ('meta_query', ());
$ meta_query () = (
'key' => SponsoMetaBox :: META_KEY,
'compare' => 'EXISTS',
);
$ query-> set ('meta_query', $ meta_query);
}
}
add_action ('pre_get_posts', 'montheme_pre_get_posts');
You can also use the filter query_vars
to allow WordPress to manage new keywords at the URL level.
function montheme_query_vars ($ params) {
$ params () = 'sponso';
return $ params;
}
add_filter ('query_vars', 'montheme_query_vars');