1. Customize
  2. Custom Functionalities
  3. [gamipress_sum_of_points] shortcode

[gamipress_sum_of_points] shortcode

The following snippet shows how to add a custom shortcode to show the sum of points of all or desired points types of an user.

Shortcode attributes:

  • points_type: Desired points types to sum, Accepts: all or any points type slug or a comma-separated list of points types slugs, Default: all
  • current_user: Set it to yes to show the points sum of current logged in user, Accepts: yes or no, Default: no
  • user_id: Specific user ID to show the points sum (requires current_user=”no”)

Examples:
Show a sum of points of all points types of the current logged in user:
[gamipress_sum_of_points current_user="yes"]
Show a sum points of Gems and Credits of the current logged in user:
[gamipress_sum_of_points points_type="gems,credits" current_user="yes"]
Show a sum points of Gems and Credits of the user with ID 1:
[gamipress_sum_of_points points_type="gems,credits" user_id="1"]

Snippet:

function my_prefix_gamipress_sum_of_points_shortcode( $atts ) {

    $atts = shortcode_atts( array(
        'points_type' => 'all',
        'user_id' => '0',
        'current_user' => 'no'
    ), $atts, 'gamipress_sum_of_points' );

    // Check desired points types
    if( $atts['points_type'] === 'all') {
        $points_types = gamipress_get_points_types_slugs();
    } else {
        $points_types = explode( ',', $atts['points_type'] );
    }

    // Force to set current user as user ID
    if( $atts['current_user'] === 'yes' ) {
        $atts['user_id'] = get_current_user_id();
    } else if( absint( $atts['user_id'] ) === 0 ) {
        $atts['user_id'] = get_current_user_id();
    }

    $sum_of_points = 0;

    foreach( $points_types as $points_type ) {

        // Ensure that this points type slug is registered
        if( ! in_array( $points_type, gamipress_get_points_types_slugs() ) ) {
            continue;
        }

        $sum_of_points += gamipress_get_user_points( $atts['user_id'], $points_type );
    }

    // Return the sum of points of all or specific points types
    return $sum_of_points;

}
add_shortcode( 'gamipress_sum_of_points', 'my_prefix_gamipress_sum_of_points_shortcode' );
Was this article helpful to you? Yes No 1

How can we help?