Ok, I modified Ryan Fugate example on Adding Custom Notifications to buddypress. I wanted to add posts notifications and it worked fine, except when I tried to filter them. First you need to know how I want to filter them. – I’ve a profile field named ‘Field’ which is a dropdown list with 5 options. – I have also 5 post categories with the exact names of the ‘Field’ values. – When a post is added, If it has (e.g. A,B,C) categories I want a notification for every user who has his ‘Field’ value is equal to A,B or C.
Here is the full code:
function custom_filter_notifications_get_registered_components( $component_names = array() ) {
if ( ! is_array( $component_names ) ) {
$component_names = array();
}
array_push( $component_names, 'custom' );
return $component_names;
}
add_filter( 'bp_notifications_get_registered_components', 'custom_filter_notifications_get_registered_components' );
function custom_format_buddypress_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' ) {
if ( 'custom_action' === $action ) {
$post = get_post( $item_id );
$recent_author = get_user_by( 'ID', $post->post_author );
$author_display_name = $recent_author->display_name;
$custom_title = $author_display_name . ' has posted a new post: ' . get_the_title($post);
$custom_text = $author_display_name. ' has posted a new post: ' . get_the_title($post);
// WordPress Toolbar
if ( 'string' === $format ) {
$return = apply_filters( 'custom_filter', '<a href="' . esc_url( get_permalink( $post ) ) . '" title="' . esc_attr( $custom_title ) . '">' . esc_html( $custom_text ) . '</a>', $custom_text, $custom_link );
// Deprecated BuddyBar
} else {
$return = apply_filters( 'custom_filter', array(
'text' => $custom_text,
'link' => $custom_link
), $custom_link, (int) $total_items, $custom_text, $custom_title );
}
return $return;
}
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 5 );
function bp_custom_add_notification( $post_id, $post_object ) {
$args = array(
'blog_id' => $GLOBALS['blog_id'],
'role' => 'employer',
'role__in' => array(),
'role__not_in' => array(),
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'meta_query' => array(),
'date_query' => array(),
'include' => array(),
'exclude' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'search' => '',
'number' => '',
'count_total' => false,
'fields' => 'all',
'who' => ''
);
$all_users = get_users($args);
foreach ($all_users as $user) {
$acc_type = xprofile_get_field_data('Field', $user->ID);
if (in_category($acc_type, $post_object->ID)) {
bp_notifications_add_notification( array(
'user_id' => $user->ID,
'item_id' => $post_id,
'component_name' => 'custom',
'component_action' => 'custom_action',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
) );
}
}
}
add_action( 'wp_insert_post', 'bp_custom_add_notification', 99, 2 );
PS: It works without the IF STATEMENT.