Last active
January 27, 2018 11:54
-
-
Save milindmore22/7472fd107299325d513e7996cd612e47 to your computer and use it in GitHub Desktop.
cached_count_user_posts
This file contains hidden or 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
<?php | |
/** | |
* Cached version of count_user_posts, which is uncached but doesn't always need to hit the db | |
* | |
* Count_user_posts is generally fast, but it can be easy to end up with many redundant queries. | |
* if it's called several times per request. This allows bypassing the db queries in favor of | |
* the cache | |
* | |
* @param int $user_id user id to get count. | |
* @param int|array $types post type array or string. | |
* @return string Count of users. | |
*/ | |
function cached_count_user_posts( $user_id, $types = 'post' ) { | |
if ( ! is_numeric( $user_id ) ) { | |
return 0; | |
} | |
$cache_key = 'cached_' . (int) $user_id; | |
$cache_group = 'user_posts_count'; | |
$count = wp_cache_get( $cache_key, $cache_group ); | |
if ( false === $count ) { | |
// @codingStandardsIgnoreLine. | |
$count = count_user_posts( $user_id, $types ); | |
// 5 Mins, We don't want to handle cache invalidation. | |
wp_cache_set( $cache_key, $count, $cache_group, 5 * MINUTE_IN_SECONDS ); | |
} | |
return $count; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment