Using WordPress ‘is_main_query()’ PHP function

The is_main_query() WordPress PHP function determines whether the query is the main query.

Usage

if (is_main_query()) {
    // Your code here
}

Parameters

  • None

More information

See WordPress Developer Resources: is_main_query()

Examples

Modify the main query to display only 3 posts per page

function modify_main_query_posts_per_page($query) {
    if ($query->is_main_query()) {
        $query->set('posts_per_page', 3);
    }
}
add_action('pre_get_posts', 'modify_main_query_posts_per_page');

Show only ‘portfolio’ post type on the main query

function display_only_portfolio_post_type($query) {
    if ($query->is_main_query()) {
        $query->set('post_type', 'portfolio');
    }
}
add_action('pre_get_posts', 'display_only_portfolio_post_type');

Exclude a category from the main query

function exclude_category_from_main_query($query) {
    if (!is_admin() && $query->is_main_query()) {
        $query->set('category__not_in', array(5));
    }
}
add_action('pre_get_posts', 'exclude_category_from_main_query');

Display only ‘published’ and ‘private’ posts in the main query

function show_published_and_private_posts($query) {
    if ($query->is_main_query()) {
        $query->set('post_status', array('publish', 'private'));
    }
}
add_action('pre_get_posts', 'show_published_and_private_posts');

Order main query posts by title in ascending order

function order_main_query_by_title($query) {
    if ($query->is_main_query()) {
        $query->set('orderby', 'title');
        $query->set('order', 'ASC');
    }
}
add_action('pre_get_posts', 'order_main_query_by_title');