From ec604f4ae04b8f7ced14fd6ecb2263b350ade2f0 Mon Sep 17 00:00:00 2001 From: spacedmonkey Date: Wed, 12 Feb 2025 21:50:28 +0000 Subject: [PATCH] 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 --- wp-includes/user.php | 14 ++++++++++++-- wp-includes/version.php | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/wp-includes/user.php b/wp-includes/user.php index ede1330251..748efa5181 100644 --- a/wp-includes/user.php +++ b/wp-includes/user.php @@ -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. diff --git a/wp-includes/version.php b/wp-includes/version.php index 1333c73110..f841209279 100644 --- a/wp-includes/version.php +++ b/wp-includes/version.php @@ -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.