[buddypress-trac] [BuddyPress Trac] #9203: Cache `BP_Groups_Member::total_group_count()`
buddypress-trac
noreply at wordpress.org
Mon Jul 1 16:56:15 UTC 2024
#9203: Cache `BP_Groups_Member::total_group_count()`
-------------------------+--------------------------
Reporter: espellcaste | Owner: espellcaste
Type: enhancement | Status: assigned
Priority: normal | Milestone: Up Next
Component: Performance | Version:
Severity: normal | Resolution:
Keywords: needs-patch |
-------------------------+--------------------------
Comment (by the ank):
Hi Mate,
I looked into the issue and I would like to add my notes here as
follows -
1. A parent function already exists **groups_total_groups_for_user()**
which caches the groups count.
2. If we directly apply the cache method to **total_group_count()**, it
would cause a problem and would not provide a refreshed count as this
function is used when someone leaves a group or joins a group and also to
get a refreshed total group count.
3. In case you would like to cache it for your purpose, please find the
code below -
{{{
public static function total_group_count( $user_id = 0 ) {
global $wpdb;
if ( empty( $user_id ) )
$user_id = bp_displayed_user_id();
$cache_key = 'total_group_count_' . $user_id;
$cached_count = get_transient( $cache_key );
if ( false === $cached_count ) {
$bp = buddypress();
if ( $user_id != bp_loggedin_user_id() &&
!bp_current_user_can( 'bp_moderate' ) ) {
$count = (int) $wpdb->get_var(
$wpdb->prepare( "SELECT COUNT(DISTINCT m.group_id) FROM
{$bp->groups->table_name_members} m, {$bp->groups->table_name} g WHERE
m.group_id = g.id AND g.status != 'hidden' AND m.user_id = %d AND
m.is_confirmed = 1 AND m.is_banned = 0", $user_id ) );
} else {
$count = (int) $wpdb->get_var(
$wpdb->prepare( "SELECT COUNT(DISTINCT m.group_id) FROM
{$bp->groups->table_name_members} m, {$bp->groups->table_name} g WHERE
m.group_id = g.id AND m.user_id = %d AND m.is_confirmed = 1 AND
m.is_banned = 0", $user_id ) );
}
// Cache the result for 1 hour (3600 seconds)
set_transient( $cache_key, $count, 3600 );
} else {
$count = $cached_count;
}
return $count;
}
}}}
Regards
--
Ticket URL: <https://buddypress.trac.wordpress.org/ticket/9203#comment:2>
BuddyPress Trac <http://buddypress.org/>
BuddyPress Trac
More information about the buddypress-trac
mailing list