Facebook comment for WordPress: Email notification on new comment

Recently I built a lyrics site in Bangla, that contains only Bangla songs. I love music and haven’t found that much lyrics site thats truly for Bangla songs and in Bangla localization, so I decided to build one. It got very popular in a few days. The songs are added by users and seems like they are loving to do that. The beauty of this site in it’s clean and structured layout, lyrics with youtube video, song classification by music composer, lyricist, singer, album and year.

Anyway, I’ve integrated facebook comments instead of regular WordPress comment system (obviously it’s built on top of WordPress, what did you think? ;) ). The most advantage of this solution is that everyone is connected and signed in at facebook all the time and can left comment easily and share them with friends. But the problem is, if anyone left a comment on a post, there is no way to be notified that any comment has been made either to the post author or to the administrator. So I came up with a quick implementation.

Loading JS SDK

Here is the code to load the Facebook JavaScript SDK asynchronously -

window.fbAsyncInit = function() {
    FB.init({
        appId      : 'YOUR_APP_ID', // App ID
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml      : true  // parse XFBML
    });
};

// Load the SDK Asynchronously
(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

New Comment Event

I’ve added a event that runs when a new comment has been made. This event sends an ajax request to WordPress to notify that a new comment has been made.

FB.Event.subscribe('comment.create', function(response) {
    var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>',
        data = {
            action: 'fb_comment_notify',
            _ajax_nonce: '<?php echo wp_create_nonce( 'fb_comment_notify' ); ?>',
            post: '<?php echo $post->ID; ?>'
        };
    
    jQuery.post(ajaxurl, data);
});

Full JS Code

window.fbAsyncInit = function() {
    FB.init({
        appId      : 'YOUR_APP_ID', // App ID
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml      : true  // parse XFBML
    });

    FB.Event.subscribe('comment.create', function(response) {
        var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>',
            data = {
                action: 'fb_comment_notify',
                _ajax_nonce: '<?php echo wp_create_nonce( 'fb_comment_notify' ); ?>',
                post: '<?php echo $post->ID; ?>'
            };
        
        jQuery.post(ajaxurl, data);
    });
    
};

// Load the SDK Asynchronously
(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

Handling Ajax Request

Now that we have sent an ajax request, we need to handle that request as well

<?php
/**
 * Handles ajax request on new Facebook comment
 */
function wedevs_fb_comment_notify() {
    $post_id = (int) $_POST['post'];
    
    check_ajax_referer( 'fb_comment_notify' );
    
    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
    $recipient = array();
    $post = get_post( $post_id );
    $recipient[] = get_option( 'admin_email' );
    $post_author = get_user_by( 'id', $post->post_author );
    
    if( !in_array( $post_author->data->user_email, $recipient ) ) {
        $recipient[] = $post_author->data->user_email;
    }
    
    $subject = sprintf( __( 'New Comment on %s', 'wedevs' ), $blogname );
    $body = sprintf( __( 'New comment on the song %s', 'wedevs' ), $post->post_title ) . "\r\n";
    $body .= sprintf( __( 'You can see all the comments of this song here: %s', 'wedevs' ), get_permalink( $post_id ) ) . "\r\n";
    
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
    $from = "From: \"$blogname\" <$wp_email>";
	$message_headers = "$from\nContent-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";

    wp_mail( $recipient, $subject, $body, $message_headers );
    exit;
}

add_action( 'wp_ajax_fb_comment_notify', 'wedevs_fb_comment_notify' );
add_action( 'wp_ajax_nopriv_fb_comment_notify', 'wedevs_fb_comment_notify' );

It sends a notification email to that administrator and the post author that a new comment has been made. Easy peasy!