is_main_query

Home » Functions » is_main_query

Function Name: is_main_query

If you’re a WordPress developer, you’re probably familiar with the concept of queries. In WordPress, queries are used to retrieve data from the database. The is_main_query function is a conditional tag that checks whether the current query is the main query.

The main query is the primary query that WordPress uses to display content on a page. For example, when you visit a category archive page, the main query is used to retrieve and display the posts from that category. Similarly, when you visit a single post page, the main query is used to retrieve and display the content of that post.

The is_main_query function returns true if the current query is the main query and false if it’s not. This is useful in situations where you want to modify the main query using pre_get_posts, but only for the main query.

Here’s an example of how you might use the is_main_query function:

function modify_main_query( $query ) {
  if ( $query->is_main_query() && $query->is_category() ) {
    // Modify the main query for category archive pages
    $query->set( 'posts_per_page', 10 );
  }
}
add_action( 'pre_get_posts', 'modify_main_query' );

In this example, we’re using the pre_get_posts action to modify the main query for category archive pages. We’re checking whether the current query is the main query using the is_main_query function, and whether it’s a category archive page using the is_category function. If both conditions are true, we’re modifying the number of posts per page to 10.

Overall, the is_main_query function is a powerful tool for WordPress developers who want to modify the main query on their site.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.