Modify Post archive Category archive page query by pre_get_posts action

Base on some specific requirement you want to do like display only specific Posts in archive page instead of all with specific ascending or Descending order and for that you need to modify Category archive page or Post archive page query Right. In wordpress with help of pre_get_posts wordpress action hook you can do without going to specific Category or post archive page .

Following are example with use of pre_get_posts action in WordPress

1. On Event Category (taxonomy) archive page limited to display 5 post per page

# 

2. On Event post archive page only display upcoming event with order base on backend setting

# 

3. Display Post Order By Modified Date in WordPress

Below example query display Post Order by post modified Date on Home page, Category archive and Search page

function lathiyasolutions_alter_query( $query )
{
    if ( $query->is_main_query() && ( $query->is_home() || $query->is_search() || $query->is_archive() )  )
    {
        $query->set( 'orderby', 'modified' );
        $query->set( 'order', 'desc' );
    }
}
add_action( 'pre_get_posts', 'lathiyasolutions_alter_query' );
Scroll to Top