Skip to content

Instantly share code, notes, and snippets.

@sbrajesh
Created September 24, 2021 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrajesh/7d9934d903a2028c1dfd4de258089e51 to your computer and use it in GitHub Desktop.
Save sbrajesh/7d9934d903a2028c1dfd4de258089e51 to your computer and use it in GitHub Desktop.
Calculate sum of given BuddyPress Xprofile field for all the user on the site
/**
* Shortcode to sum all the values of the given xprofile field.
*
* @param int|string $field field id or name.
*
* Example 1:- Total Cows owned by our members [xprofile-field-sum field="Number of Cows you Own"]
* Example 2:- Total Cows owned by our members [xprofile-field-sum field=32]
*/
add_shortcode( 'xprofile-field-sum', function ( $atts = array(), $content = '' ) {
if ( ! class_exists( '\BP_XProfile_Field' ) ) {
return '';
}
$atts = shortcode_atts( array(
'field' => '',
), $atts );
if ( empty( $atts['field'] ) ) {
return '';
}
if ( is_numeric( $atts['field'] ) ) {
$field_id = (int) $atts['field'];
} else {
$field_id = BP_XProfile_Field::get_id_from_name( $atts['field'] );
}
$bp = buddypress();
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( "SELECT SUM(value) FROM {$bp->profile->table_name_data} WHERE field_id=%d", $field_id ) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment