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!

Debugging Zend Framework using firebug

You can use firebug to debug your Zend Framework application. May be you are using print_r(), var_dump() or Zend_Debug::dump($var), they prints the information in your application. But, with the help of FirePHP add-on for Firebug, we will be able to dump our variable on firebug console :D

First install the FirePHP add-on for your Firebug. Then you can use the following snippet anywhere to dump your variables to firebug console -

$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log( $writer );
$logger->log('My Sample Log', Zend_Log::DEBUG);

The second parameter of the Zend Logger is a constant. You can use 0-7 (zero to seven) as a parameter. Here is the details – Continue reading

Is javascript enabled?

Sometimes we need to check that if javascript is enabled. To do this, we will add some codes. It will show, if only javascript is disabled.

<NOSCRIPT>
<H3>Your JavaScript is disabled</H3>
<strong>For Internet Explorer</strong><br />
Go to "View -> Internet Options -> Security tab<br />
Select "Custom" and click on the "Settings..." button<br />
To enable: make sure "Enable" is selected under "Active scripting"<br />
To disable: make sure "Disable" is selected under "Active scripting"<br /><br />

<strong>For FireFox</strong><br />
Go to "Tools" -> "Options"<br />
Go to "Content" tab and "Enable JavaScript"<br /><br />

<strong>For Opera</strong><br />
Go to "Tools" -> "Preferences"<br />
Go to "Advanced" tab -> "Content" and "Enable JavaScript"<br /><br />
</div>
</NOSCRIPT>

Everything under <noscript></noscript> will be escaped, if javascript is enabled