Make WordPress Core


Ignore:
Timestamp:
02/12/2025 09:48:04 PM (2 months ago)
Author:
spacedmonkey
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/user.php

    r59754 r59817  
    605605    global $wpdb;
    606606
     607    $post_type = array_unique( (array) $post_type );
     608    sort( $post_type );
     609
    607610    $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
    608 
    609     $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
     611    $query = "SELECT COUNT(*) FROM $wpdb->posts $where";
     612
     613    $last_changed = wp_cache_get_last_changed( 'posts' );
     614    $cache_key    = 'count_user_posts:' . md5( $query ) . ':' . $last_changed;
     615    $count        = wp_cache_get( $cache_key, 'post-queries' );
     616    if ( false === $count ) {
     617        $count = $wpdb->get_var( $query );
     618        wp_cache_set( $cache_key, $count, 'post-queries' );
     619    }
    610620
    611621    /**
Note: See TracChangeset for help on using the changeset viewer.