Writing a plugin that notify my friends of new post that mentions(@) them

Twice edited according to kaiser’s suggestions, unsecure version removed.

<?php
function my_email_friend($post_id = '') {
    // get post object
    $post = get_post($post_id);
    // get post content
    $content = $post->post_content;
    // if @David exists
    if( 0 !== preg_match('/(@\w)/', $content, $matches) )
        $friend_display_name_like="%" . like_escape($matches[0]) . '%';
    else
        return; // do nothing if no matches
    global $wpdb;
    // get friend email by 'display_name'
    $friend_email = $wpdb->get_var( $wpdb->prepare( "
        SELECT user_email
        FROM $wpdb->users
        WHERE display_name
        LIKE %s ",
        $friend_display_name_like
    )) ;
    if($friend_email) {
        /* Your  code here, 'mail()' can use '$friend_email' */
    }
}
add_action('publish_post', 'my_email_friend');

Use it only as starting point because:

  • the code is partially tested (read: untested);
  • you can mention many friends in the post, the first mentioned will be notified (could be enhanced);
  • you can have something like [email protected] in the post content. The script will try to find ‘example’ user;
  • only one John from both John Doe and John Roe will be e-mailed.

Everything to be enhanced, but seems like ready to test.

Leave a Comment