How to add custom badges to the new Badges extension?

Hey,

I haven’t had a proper look through the new Badges extension yet, but no doubt someone in the community (or myself!) will want to add in some custom badges soon. Are there any recommended hooks, actions, or documentation available, or perhaps a quick code snippet we could follow as an example?

Cheers,
Chris :victory_hand:

Hi Chris,

It’s possible to add a new metric to the drop-down this way:

add_filter( 'hivepress/v1/meta_boxes/badge_settings', 'hp_add_badge_criteria' );
add_filter( 'hivepress/v1/models/badge', 'hp_add_badge_criteria' );

function hp_add_badge_criteria( $model ) {
    $model['fields']['criterion']['options']['custom_metric'] = 'Custom Metric';

    return $model;
}

Implementing the logic behind it is a bit more complex, the hook depends on the metric – for example, the Favorites Received one uses hivepress/v1/models/favorite/create and hivepress/v1/models/favorite/delete hooks to re-calculate the number of favorites only when it changes. There’s a function that can be called to add/remove a badge (based on the calculated number), but it’s not available outside of the extension code at the moment; we’ll make it public in the next update:

hivepress()->badge->update_awards( $user_id, $metric, $threshold );

For the example above, it would be called like this:

hivepress()->badge->update_awards( $user_id, 'favorites_received', 123 );

This function would go through the badges with ‘favorites_received’ metric selected, and award the first badge passing the threshold, also cleaning up any other badges with the same metric selected.

Hope this helps

1 Like

Many thanks for this @Ihor! :folded_hands:

I’ve a few ideas for the next update, but I’ll post them as a feature request.

Cheers,
Chris :victory_hand: