Make WordPress Core


Ignore:
Timestamp:
06/14/2016 01:59:25 AM (10 years ago)
Author:
boonebgorges
Message:

Query: Allow plugins to supply post results instead of having WP_Query fetch them from the database.

Returning a non-null value from the new posts_pre_query filter will cause
WP_Query to skip its database query, so that posts data can be provided from
elsewhere. This is useful in cases where post data may be mirrored in a
separate location, such as an external search application.

Developers should note that the WP_Query properties generally used to
calculate pagination - specifically, found_posts and max_num_pages, which
are determined by default in set_found_posts() - must be provided explicitly
when using the posts_pre_query filter; since WP_Query will not be
contacting the database, it will have no access to SELECT FOUND_ROWS().
The WP_Query instance is passed to posts_pre_query by reference, so that
these properties can be set manually if needed.

Props jpdavoutian, tlovett1.
Fixes #36687.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/post/query.php

    r37225 r37692  
    389389                $this->assertEqualSets( $requested, $actual_posts );
    390390        }
     391
     392        /**
     393         * @ticket 36687
     394         */
     395        public function test_posts_pre_query_filter_should_bypass_database_query() {
     396                global $wpdb;
     397
     398                add_filter( 'posts_pre_query', array( __CLASS__, 'filter_posts_pre_query' ) );
     399
     400                $num_queries = $wpdb->num_queries;
     401                $q = new WP_Query( array(
     402                        'fields' => 'ids',
     403                        'no_found_rows' => true,
     404                ) );
     405
     406                remove_filter( 'posts_pre_query', array( __CLASS__, 'filter_posts_pre_query' ) );
     407
     408                $this->assertSame( $num_queries, $wpdb->num_queries );
     409                $this->assertSame( array( 12345 ), $q->posts );
     410        }
     411
     412        public static function filter_posts_pre_query( $posts ) {
     413                return array( 12345 );
     414        }
    391415}
Note: See TracChangeset for help on using the changeset viewer.