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

[gamipress_earned_achievements_count] shortcode

The following snippet shows how to add a custom shortcode to show the number of achievements earned of all or desired achievement types of an user.

Shortcode attributes:

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

Examples:
Show the number of achievements earned of all achievement types of the current logged in user:
[gamipress_earned_achievements_count current_user="yes"]
Show the number of Badges and Quest earned of the current logged in user:
[gamipress_earned_achievements_count achievement_type="badges,quests" current_user="yes"]
Show the number of Badges and Quest earned of the user with ID 1:
[gamipress_earned_achievements_count achievement_type="badges,quests" user_id="1"]

Snippet:

function my_prefix_gamipress_earned_achievements_count_shortcode( $atts ) {

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

    // Check desired points types
    if( $atts['achievement_type'] === 'all') {
        $achievement_types = gamipress_get_achievement_types_slugs();
    } else {
        $achievement_types = explode( ',', $atts['achievement_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();
    }

    $earned_achievements = 0;

    foreach( $achievement_types as $achievement_type ) {

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

        $earned_achievements += count( gamipress_get_user_achievements( array(
            'user_id'           => $atts['user_id'],
            'achievement_type'  => $achievement_type,
        ) ) );
    }

    // Return the sum of achievements earned of all or specific points types
    return $earned_achievements;

}
add_shortcode( 'gamipress_earned_achievements_count', 'my_prefix_gamipress_earned_achievements_count_shortcode' );
Was this article helpful to you? Yes No

How can we help?