Skip to content

Commit

Permalink
Query: Cache the result when get_pages() doesn't find anything in t…
Browse files Browse the repository at this point in the history
…he database.

Props flixos90, soulseekah.
Fixes #43514.



git-svn-id: https://develop.svn.wordpress.org/trunk@44587 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
pento committed Jan 14, 2019
1 parent 464c9a7 commit 5cdc0e1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/wp-includes/post.php
Expand Up @@ -5057,7 +5057,8 @@ function get_pages( $args = array() ) {
$last_changed = wp_cache_get_last_changed( 'posts' );

$cache_key = "get_pages:$key:$last_changed";
if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
$cache = wp_cache_get( $cache_key, 'posts' );
if ( false !== $cache ) {
// Convert to WP_Post instances.
$pages = array_map( 'get_post', $cache );
/** This filter is documented in wp-includes/post.php */
Expand Down Expand Up @@ -5218,6 +5219,8 @@ function get_pages( $args = array() ) {
$pages = $wpdb->get_results( $query );

if ( empty( $pages ) ) {
wp_cache_set( $cache_key, array(), 'posts' );

/** This filter is documented in wp-includes/post.php */
$pages = apply_filters( 'get_pages', array(), $r );
return $pages;
Expand Down
22 changes: 22 additions & 0 deletions tests/phpunit/tests/post/getPages.php
Expand Up @@ -700,4 +700,26 @@ function test_exclude_tree() {
$exclude6 = get_pages( array( 'exclude_tree' => array( $post_id1, $post_id3 ) ) );
$this->assertCount( 2, $exclude6 );
}

/**
* @ticket 43514
*/
function test_get_pages_cache_empty() {
global $wpdb;

wp_cache_delete( 'last_changed', 'posts' );
$this->assertFalse( wp_cache_get( 'last_changed', 'posts' ) );

$num_queries = $wpdb->num_queries;

$pages = get_pages(); // Database gets queried

$this->assertEquals( $num_queries + 1, $wpdb->num_queries );

$num_queries = $wpdb->num_queries;

$pages = get_pages(); // Database should not get queried

$this->assertEquals( $num_queries, $wpdb->num_queries );
}
}

0 comments on commit 5cdc0e1

Please sign in to comment.