Search code examples
phpfacebookfacebook-comments

Show Facebook Comment Count In Blog (Not Wordpress)


I'm planning on using facebook comments plugin for my new blog website and would like to show some stats in the article header (Date, Views, Times Commented, etc) but I can't get the facebook view count to show up. Here's the code I have at the moment:

<div id="fb-root"></div>
<script>
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&appId=277028005786031&version=v2.0";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

At display position

<b>Commented On:</b> <fb:comments-count href="http://example.com/"></fb:comments-count> Times

All this shows on the page is:

Commented On: Times

How can I get it to display the actual number of posts?


Solution

  • As of API 2.0 each API request requires a valid access_token and from your code I see that you are using 2.0, This means sending sensitive data to the Graph which is not safe at all, if you're using JS

    A valid access_token

    • App access_token, combination of in app id & secret in this form {app_id}|{app_secret} (recommended because it doesn't expire)

    • a user access_token, issued by authorizing an app (expires after 2 hour of issuing, 60 days after extending)

    Solution #1 (easy)

    Switch back to API v1.0, available until **April 30th, 2015

    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&appId={app_id}&version=v1.0";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    

    Solution #2 (advance)

    You tagged PHP, so the solution i will post is for future use,

    comments-count.php

    <?php
    
    header('Content-Type: application/json');
    
    $config = array('appId'  => '{Your-app-Id}',
                    'secret' => '{Your-app-secret}');
    
    /** If the $_GET['href'] is set and not empty **/
    if( isset($_GET['href']) && !empty($_GET['href']) ) {
    
        $href = $_GET['href']; 
        $commentsCount = getCommentsCount($href);
    
        // check if the HREF has comments count
        if ( array_key_exists('comments', $commentsCount) ) {
            $comments = $commentsCount['comments'];
        } else {
            $comments = 0;
        }
    
        echo json_encode( array('meta'     => array('code' => 200),
                                'id'       => $commentsCount['id'],
                                'comments' => $comments,
                                'shares'   => $commentsCount['shares']), JSON_PRETTY_PRINT);
    
    } else {
    
        /** else print the error below (JOSN encoded) **/
        header('HTTP/1.1 400');
        echo json_encode( array('meta'          => array('code' => 400),
                                'message' => 'href is not provided'), JSON_PRETTY_PRINT);
        // JSON_PRETTY_PRINT requires PHP 5.4 or higher, you should remove it if you have 5.3 or lower
    }
    
    function getCommentsCount($href) {
        global $config;
        $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.0/?id='. $href . '&access_token=' . $config['appId'] . '|' . $config['secret']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $r  = curl_exec($ch);
        return json_decode($r, true);
    }
    

    comments-count.js

    ;(function($) {
    
        $.fn.facebookCommentsCount = function( options ) {
    
                var $target = this;
    
                /** Plugin default settings **/
                var settings = $.extend({
    
                        apiPath          : 'fb-comments-count/comments-count.php', // Path to `comments-count.php`
                        zeroComments     : null,
                        oneComment       : null,
                        multipleComments : null
    
                }, options);
    
    
                return $target.each( function() {
    
                    var href = $(this).attr('data-href');
                    var $this = $(this)
    
                    $.ajax({
                        url:  settings.apiPath,
                        type: 'GET',
                        dataType: 'json',
                        data: { href : href },
                        success: function(data) {
    
                            if (data.comments === 0) {
    
                                if(settings.zeroComments) {
                                    $this.html(data.comments + '&nbsp;' + settings.zeroComments);
                                } eles {
                                    $this.html(data.comments);
                                }
    
                            } else if (data.comments === 1 ) {
    
                                if(settings.oneComment) {
                                    $this.html( data.comments + '&nbsp;' + settings.oneComment);
                                } else {
                                    $this.html(data.comments);
                                }
    
                            } else {
    
                                if(settings.multipleComments) {
                                    $this.html( data.comments + '&nbsp;' + settings.multipleComments);
                                } else {
                                    $this.html(data.comments);
                                }
    
                            }
    
                        },
                        error: function(error) {
                          console.log(error);
                        }
                    });
    
                });
    
        };
    
    }(jQuery));
    

    How-To Use

    In your page add div, span or p (inline elements are better, div is block)

    <div class="fb-comments-count" data-href="{URL}">0</dvi>
    
    <script>
    $('.fb-comments-count').facebookCommentsCount();
    </script>
    

    GitHub

    Demo