WordPress pre_get_posts example
Here is a quick example showing how to modify the main WP Query (Loop) using the pre_get_posts
filter hook.
Most functions that hook into pre_get_posts
tend to look very similar. Something like this:
function shapeSpace_modify_main_query($query) {
if (!is_admin() && $query->is_main_query()) {
$query->set('post_type', 'download');
$query->set('orderby', 'ID');
$query->set('order', 'ASC');
}
}
add_action('pre_get_posts', 'shapeSpace_modify_main_query');
That’s the basic idea. Here is what is happening with the code:
- The
$query
variable is passed to the function - Check if the query is not for an admin page, AND is the main query
- If yes, then the
set
method is used several times to modify the query - Lastly the function is connected to the
pre_get_posts
hook viaadd_action()
So how is the query modified with this example? Let’s break it down:
- set(‘post_type’, ‘page’); — sets the post type to page
- set(‘orderby’, ‘ID’); — sets the orderby parameter to sort by ID
- set(‘order’, ‘ASC’); — sets the display order to ascending
And there are tons more parameters that can be customized. For a complete list, check out the WP_Query documentation at WordPress.org. Also here is the documentation for the pre_get_posts hook. And check out DigWP.com for even more ways to customize the WordPress Loop.