Users: Add caching to count_user_posts function

Introduced caching for the `count_user_posts` function to reduce redundant database queries. This ensures better performance by storing and reusing query results when possible. Additionally, sanitized and sorted the `$post_type` array to avoid invalid queries.

Props spacedmonkey, peterwilsoncc, mamaduka, flixos90, johnjamesjacoby, swissspidy, dilip2615, johnregan3, wpgurudev, desrosj, milindmore22, Krstarica, dilipom13.
Fixes #39242.
Built from https://develop.svn.wordpress.org/trunk@59817


git-svn-id: http://core.svn.wordpress.org/trunk@59159 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
spacedmonkey 2025-02-12 21:50:28 +00:00
parent 9724765081
commit ec604f4ae0
2 changed files with 13 additions and 3 deletions

View File

@ -604,9 +604,19 @@ function wp_validate_logged_in_cookie( $user_id ) {
function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
$post_type = array_unique( (array) $post_type );
sort( $post_type );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
$query = "SELECT COUNT(*) FROM $wpdb->posts $where";
$last_changed = wp_cache_get_last_changed( 'posts' );
$cache_key = 'count_user_posts:' . md5( $query ) . ':' . $last_changed;
$count = wp_cache_get( $cache_key, 'post-queries' );
if ( false === $count ) {
$count = $wpdb->get_var( $query );
wp_cache_set( $cache_key, $count, 'post-queries' );
}
/**
* Filters the number of posts a user has written.

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.8-alpha-59816';
$wp_version = '6.8-alpha-59817';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.