Skip to content

Instantly share code, notes, and snippets.

@mycred
Created July 19, 2018 10:48
Show Gist options
  • Save mycred/47e15a5a9c49f25b23f7dc4006d95840 to your computer and use it in GitHub Desktop.
Save mycred/47e15a5a9c49f25b23f7dc4006d95840 to your computer and use it in GitHub Desktop.
This is an example how you can add BuddyPress notifications for users when they gain / lose myCRED points.
/**
* Register Custom BP Notifications
* Inform BuddyPress about our custom myCRED related notifications.
* @since 1.0
* @version 1.0
*/
function mycredpro_register_custom_bp_notifications() {
buddypress()->mycred_notifications = new stdClass;
buddypress()->mycred_notifications->notification_callback = 'mycredpro_render_bp_notification';
buddypress()->active_components['mycred_notifications'] = 1;
}
add_action( 'bp_setup_globals', 'mycredpro_register_custom_bp_notifications' );
/**
* Capture myCRED Event
* Whenever we add to the log we add a notification.
* @since 1.0
* @version 1.0
*/
function mycredpro_log_to_bp_notification( $insert_id, $request ) {
if ( $insert_id === false ) return $insert_id;
extract( $request );
if ( function_exists( 'bp_notifications_add_notification' ) )
bp_notifications_add_notification( array(
'user_id' => $user_id,
'item_id' => $insert_id,
'secondary_item_id' => $user_id,
'component_name' => 'mycred_notifications',
'component_action' => 'mycred_points'
) );
return $insert_id;
}
add_filter( 'mycred_new_log_entry_id', 'mycredpro_log_to_bp_notification', 90, 2 );
/**
* Render Notification
* Help BuddyPress out by rendering the log entry into something it can understand.
* @since 1.0
* @version 1.0.1
*/
function mycredpro_render_bp_notification( $action, $item_id, $secondary_item_id, $total_items, $format = 'string', $id = 0 ) {
$return = false;
if ( $action == 'mycred_points' ) {
global $wpdb, $mycred;
$text = $link = '';
$entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$mycred->log_table} WHERE id = %d;", $item_id ) );
if ( isset( $entry->id ) ) {
$mycred = mycred( $entry->ctype );
// In this example we link to the ledger in the users profile
// this needs to be changed to the URL you have setup (if you have this enabled)
// or to something specific.
$link = bp_loggedin_user_domain() . 'points-ledger/';
$text = $mycred->parse_template_tags( $entry->entry, $entry );
$title = strip_tags( $text );
}
}
if ( 'string' == $format ) {
$return = '<a href="' . esc_url( $link ) . '" title="' . esc_attr( $title ) . '">' . esc_html( $text ) . '</a>';
}
else {
$return = array(
'text' => $text,
'link' => $link
);
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment