Created
August 23, 2017 18:41
-
-
Save lukecav/cdfc051aed1403f8ed2bff25f366450e to your computer and use it in GitHub Desktop.
Reducing postmeta queries with update_meta_cache()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'posts_results', 'cache_meta_data', 9999, 2 ); | |
function cache_meta_data( $posts, $object ) { | |
$posts_to_cache = array(); | |
// this usually makes only sense when we have a bunch of posts | |
if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) < 3 ) | |
return $posts; | |
foreach( $posts as $post ) { | |
if ( isset( $post->ID ) && isset( $post->post_type ) ) { | |
$posts_to_cache[$post->ID] = 1; | |
} | |
} | |
if ( empty( $posts_to_cache ) ) | |
return $posts; | |
update_meta_cache( 'post', array_keys( $posts_to_cache ) ); | |
unset( $posts_to_cache ); | |
return $posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/
https://developer.wordpress.org/reference/functions/update_meta_cache/