Skip to content

Instantly share code, notes, and snippets.

@fovoc
Forked from modemlooper/custom-notification.php
Last active December 7, 2020 03:13
Show Gist options
  • Save fovoc/d64a6b7a183a928bb10bdbff7417cef1 to your computer and use it in GitHub Desktop.
Save fovoc/d64a6b7a183a928bb10bdbff7417cef1 to your computer and use it in GitHub Desktop.
BuddyPress add custom notification
<?php
// this is to add a fake component to BuddyPress. A registered component is needed to add notifications
function custom_filter_notifications_get_registered_components( $component_names = array() ) {
// Force $component_names to be an array
if ( ! is_array( $component_names ) ) {
$component_names = array();
}
// Add 'custom' component to registered components array
array_push( $component_names, 'custom' );
// Return component's with 'custom' appended
return $component_names;
}
add_filter( 'bp_notifications_get_registered_components', 'custom_filter_notifications_get_registered_components' );
// this gets the saved item id, compiles some data and then displays the notification
function custom_format_buddypress_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' ) {
// New custom notifications
if ( 'custom_action' === $action ) {
$title = get_the_title( $item_id );
$link = get_the_permalink( $item_id );
$text = 'New blog post published: '.$title;
// WordPress Toolbar
if ( 'string' === $format ) {
$return = apply_filters( 'custom_filter', '<a href="' . esc_url( $link ) . '" title="' . esc_attr( $title ) . '">' . esc_html( $text ) . '</a>', $title, $link );
// Deprecated BuddyBar
} else {
$return = apply_filters( 'custom_filter', array(
'text' => $text,
'link' => $link
), $link, (int) $total_items, $title, $title );
}
return $return;
}
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 5 );
// this hooks to comment creation and saves the comment id
function bp_custom_add_notification( $post_id ) {
$post = get_post( $post_id );
$author_id = $post->post_author;
bp_notifications_add_notification( array(
'user_id' => $author_id,
'item_id' => $post_id,
'component_name' => 'custom',
'component_action' => 'custom_action',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
) );
}
add_action( 'save_post', 'bp_custom_add_notification', 99, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment