do_action_ref_array( 'pre_get_posts', WP_Query $this )

Fires after the query variable object is created, but before the actual query is run.

Description Description

Note: If using conditional tags, use the method versions within the passed instance (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions like is_main_query() test against the global $wp_query instance, not the passed one.

Parameters Parameters


(WP_Query) The WP_Query instance (passed by reference).

Top ↑

Source Source

File: wp-includes/class-wp-query.php

View on Trac

Top ↑

Changelog Changelog

Version Description
2.0.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by seabluetom
    *		The Code below will modify the main WordPress loop, before the queries fired,
    *	to only show posts in the halloween category on the home page.
    	function sbt_exclude_category($query){
    		if ( $query->is_home() && $query->is_main_query() && ! is_admin() ) {
    			$query->set( 'category_name', 'halloween' );
  2. Skip to note 2 content
    Contributed by saddamcrr7

    Example for how to universally adjust queries for an ‘event’ post type:

    function university_adjust_queries($query){
       if ( ! is_admin() && is_post_type_archive( 'event' ) && $query->is_main_query() ) {
            $query->set( 'meta_key', 'event_date' );
            $query->set( 'orderby', 'meta_value_num' );
            $query->set( 'order', 'ASC');
            $query->set( 'meta_query', array(
                    'key'     => 'event_date',
                    'compare' => '>=',
                    'value'   => date('Ymd'),
                    'type'    => 'numeric',
            ) );
    add_action( 'pre_get_posts', 'university_adjust_queries' );

You must log in before being able to contribute a note or feedback.