A quick way to fix the broken pagination on your WordPress category or archive pages when using custom queries

Here is the useful code snippet that I use to fix the issue where using a custom query on a WordPress category or archive or even index page breaks the pagination.

Simply copy and paste this code into your theme’s functions file:

function my_post_queries( $query ) {
 // do not alter the query on wp-admin pages and only alter it if it's the main query
 if (!is_admin() && $query->is_main_query()){
// alter the query for the home page
 $query->set('posts_per_page', 3);
 $query->set('cat', '9');
add_action( 'pre_get_posts', 'my_post_queries' );

And then edit as necessary!

To target a specific category, you would use this code:

 // alter the query for the Apples category page 
      $query->set('posts_per_page', 6);

I have found this to be one of the easiest ways to fix the pagination issues I have run into when using custom WordPress queries. Let me know if you have a different or better way of doing so 🙂