WordPress

WordPress TutorialRemove Version from WordPress and StylesheetsRun WordPress local with XAMPPSecurity in WordPress - EscapingSecurity in WordPress - SanitizationThe Loop (main WordPress loop)Update WordPress ManuallyWordPress Actions and FiltersWordPress add action()WordPress add editor style()WordPress add menu page()WordPress Add ShortcodeWordPress add submenu page()WordPress add theme support()WordPress Add/remove contact info for users with user contactmethods filter hookWordPress Admin Dashboard WidgetsWordPress AJAXWordPress Alternating main loop (pre get posts filter)WordPress Child Theme BasicsWordPress Create a Post ProgrammaticallyWordPress Create Template for Custom Post TypeWordPress Creating a custom templateWordPress Custom exerpts with excerpt length and excerpt moreWordPress Custom Post TypesWordPress Customizer Basics (Add Panel, Section, Setting, Control)WordPress Customizer Hello WorldWordPress DebuggingWordPress Enqueuing scriptsWordPress Enqueuing StylesWordPress Function : wp trim words()WordPress Function: add action()WordPress get bloginfo()WordPress get home path()WordPress get option()WordPress get permalink()WordPress get template part()WordPress get the category()WordPress get the title()WordPress home url()WordPress How Can I integrate Markdown editor with Advance Custom Fields repeater Add-on.WordPress initWordPress Installation and ConfigurationWordPress Making network requests with HTTP APIWordPress Meta BoxWordPress Options APIWordPress Plugin creationWordPress Plugin developmentWordPress Post FormatsWordPress Querying postsWordPress Remove Auto Line Breaks from Content and ExcerptWordPress REST APIWordPress Secure your installationWordPress ShortcodeWordPress Shortcode with attributeWordPress ShortcodesWordPress SidebarsWordPress Site MigrationWordPress TaxonomiesWordPress Template hierarchyWordPress template includeWordPress the $wpdb ObjectWordPress the Admin Bar (aka The Toolbar)WordPress the title()WordPress theme and child-theme developmentWordPress ThemesWordPress wp get current user()WordPress WP Query() LoopWordPress WP-CLIWordPress WP-Cron



WordPress Alternating main loop (pre get posts filter)

From WikiOD

Syntax[edit | edit source]

  • add_action( 'pre_get_posts', 'callback_function_name' );
  • function callback_function_name( $query ) {}
  • // for PHP 5.3.0 or above
  • add_action( 'pre_get_posts', function( $query ){} );

Parameters[edit | edit source]

Parameter Details
$query (WP_Query) Loop object

Remarks[edit | edit source]

If you are using PHP 5.3.0 or above, you can use closures (anonymous functions)

add_action( 'pre_get_posts', function( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    // this code will run only if
    // - this query is main query
    // - and this is not admin screen
});

Change posts_per_page for main loop[edit | edit source]

All we need to do is to use set() method of $query object.

It takes two arguments, first what we want to set and second what value to set.

add_action( 'pre_get_posts', 'change_posts_per_page' );

function change_posts_per_page( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    $query->set( 'posts_per_page', 5 );
    return;
}

Even more specific loop targeting[edit | edit source]

Let's say we want to change main loop, only for specific taxonomy, or post type.

Targeting only main loop on book post type archive page.

add_action( 'pre_get_posts', 'my_callback_function' );

function my_callback_function( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;
    if( !is_post_type_archive( 'book' ) ) return;

    // this code will run only if
    // - this query is main query
    // - and this is not admin screen
    // - and we are on 'book' post type archive page
}

You can also check for category, tag or custom taxonomy archive page using is_category(), is_tag() and is_tax().

You can use any conditional tag available in WordPress.

Show posts from only one category[edit | edit source]

add_action( 'pre_get_posts', 'single_category' );

function single_category( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    $query->set( 'cat', '1' );
    return;
}

Pre get posts filter basic usage[edit | edit source]

Sometimes you would like to change main WordPress query.

Filter pre_get_posts is the way to go.

For example using pre_get_posts you can tell main loop to show only 5 posts. Or to show posts only from one category, or excluding any category etc.

add_action( 'pre_get_posts', 'my_callback_function' );

function my_callback_function( $query ) {
    // here goes logic of your filter
}

As you can see, we are passing main loop query object into our callback function argument.

Important note here: we are passing argument as a reference. It means that we do not need to return query or set any globals to get it working. As $query is a reference to the main query object, all changes we make on our object are immediately reflected in the main loop object.

Exclude category from posts list edit share[edit | edit source]

add_action( 'pre_get_posts', 'single_category_exclude' );

function single_category_exclude( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    $query->set( 'cat', '-1' );
    return;
}

Targeting only main WordPress loop[edit | edit source]

WordPress is applying pre_get_posts filter to literally any loop it generates. It means that all changes we are making in our callback function are applied to all exiting loops.

Obviously it is not what we want in most scenarios.

In most cases we would like to target only main loop, and only for non-admin screens.

We can use is_main_query() method and is_admin() global function to check if we are in the right place.

add_action( 'pre_get_posts', 'my_callback_function' );

function my_callback_function( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    // this code will run only if
    // - this query is main query
    // - and this is not admin screen
}

This article is an extract of the original Stack Overflow Documentation created by contributors and released under CC BY-SA 3.0. This website is not affiliated with Stack Overflow