Opened 14 months ago
Closed 13 months ago
#20236 closed defect (bug) (fixed)
Improper testing of cache retrievals causes wasted queries.
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | 3.4 |
| Component: | Cache | Version: | |
| Severity: | normal | Keywords: | has-patch |
| Cc: |
Description
wp_cache_get() can retrieve values such as the empty array which is considered false by the ! test. The following function is incorrect because it will always ignore the cache and repeat the get_col and wp_cache_add when the cache contains the empty array. This occurs on sites which have no pages.
function get_all_page_ids() {
global $wpdb;
if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
wp_cache_add('all_page_ids', $page_ids, 'posts');
}
return $page_ids;
}
The cache check should be written with an understanding of the return type of $wpdb->get_col() (array). Here it is with the check fixed:
function get_all_page_ids() {
global $wpdb;
$page_ids = wp_cache_get('all_page_ids', 'posts');
if ( ! is_array( $page_ids ) ) {
$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
wp_cache_add('all_page_ids', $page_ids, 'posts');
}
return $page_ids;
}
Patch 1 fixes this occurrence. Please keep this ticket open until all similar occurrences are found and fixed.
Attachments (1)
Change History (5)
- Component changed from General to Cache
- Keywords has-patch added
- Milestone changed from Awaiting Review to 3.4
I always thought that (bool) array() evaluates to true, but that's obviously not the case:

fix get_all_page_ids()