How to modify the default WordPress query using pre_get_posts()

by Dan
Last updated: September 26th, 2020

For the longest time whenever I needed to customise the WordPress loop my go to would be to use the WP_query function, but then I learned of a better and more performant method using WordPress’s pre_get_posts() function which allows us to modify the main query, rather than creating an entirely new one.

Unless I need to output multiple loops on a page, modifying the query using the pre_get_posts() is now the function I reach for.

// Modifies the Default loop query for posts to return a random order function override_posts_query( $query ) { if ( is_post_type_archive( 'posts' ) && $query->is_main_query() ) { $query->set( 'orderby', 'rand' ); $query->set( 'order', 'DSC' ); $query->set( 'posts_per_page', 12 ); // these are just examples of how you might modify a query. //Update these as needed to fit what you're trying to do. } } add_filter( 'pre_get_posts', 'override_posts_query' );
Code language: PHP (php)

we think you'll probably like these too