Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count together facebook, twitter and g+ "shares" and store them in database?

I was working on my Word Press side and got this idea. Instead of implementing a "Like/Fav" feature to determine top articles, I would like to instead count together how many facebook shares, tweets and +1 that article received and once they are all counted together store them in database (with according article), so I can than choose top articles by selecting out ones with most shares, tweets and +1's. I would also need to update database every time user clicks on either of the facebook, twitter or g+ buttons.

Is this achievable within Word Press and by use of their api's?

like image 900
Ilja Avatar asked Feb 28 '13 12:02

Ilja


1 Answers

This is not as simple as it looks like.

There is a great gist on GitHub with all the APIs you want to implement: Get the share counts from various APIs.

You can connect to these servers and fetch data using jQuery and AJAX:

function how_many_tweets(url, post_id) {
    var api_url = "http://cdn.api.twitter.com/1/urls/count.json";
    var just_url = url || document.location.href;
    $.ajax({
        url: api_url + "?callback=?&url=" + just_url,
        dataType: 'json',
        success: function(data) {
            var tweets_count = data.count;
            // do something with it
        }
    });
}

function how_many_fb_shares(url, post_id) {
    var api_url = "http://api.facebook.com/restserver.php";
    var just_url = url || document.location.href;
    $.ajax({
        url: api_url + "?method=links.getStats&format=json&urls=" + just_url,
        dataType: 'json',
        success: function(data) {
            var shares_count = data[0].total_count;
            // do something with it
        }
    });
};

function how_many_google_pluses(url, api_key, post_id) {
    var api_url = "https://clients6.google.com/rpc?key=" + api_key;
    var just_url = url || document.location.href;
    $.ajax({
        url: api_url,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        processData: false,
        data: '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' + just_url + '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]',
        success: function(data) {
            var google_pluses = data.result.metadata.globalCounts.count;
            // do something with it
        }
    })
}

Then, you can replace // do something with it lines with another AJAX request to your blog. You will need to write a plugin to handle this request and save the data in the $wpdb. The plugin is relatively simple:

<?php

/*
    Plugin Name: Save Share Count Request Plugin
    Plugin URI: http://yourdomain.com/
    Description: This plugin catches 'save share count' requests and updates the database.
    Version: 1.0

*/

// check if request is a 'save share count' request
// i'm using sscrp_ prefix just not to redefine another function
// sscrp_ means SaveShareCountRequestPlugin_
function sscrp_is_save_share_count_request() {
    if(isset($_GET['_save_share_count_request'])) return true;
    else return false;
}

// save the count in database
function sscrp_save_share_count_in_wpdb($type, $count, $post_id) {

    // $count is your new count for the post with $post_id
    // $type is your social media type (can be e.g.: 'twitter', 'facebook', 'googleplus')
    // $post_id is post's id

    global $wpdb;

    // create a $wpdb query and save $post_id's $count for $type.
    // i will not show how to do it here, you have to work a little bit

    // return true or false, depending on query success.

    return false;
}

// catches the request, saves count and responds
function sscrp_catch_save_share_count_request() {
    if(sscrp_is_save_share_count_request()) {
        if(isset($_GET['type'])) {
            $social_media_type = $_GET['type'];
            $new_count = $_GET['value'];
            $post_id = $_GET['post_id'];
            if(sscrp_save_share_count_in_wpdb($social_media_type, $new_count, $post_id)) {
                header(sprintf('Content-type: %s', 'application/json'));
                die(json_encode(array("sscrp_saved"=>true)));
            } else {
                header(sprintf('Content-type: %s', 'application/json'));
                die(json_encode(array("sscrp_saved"=>false)));
            }
        } else {
            header(sprintf('Content-type: %s', 'application/json'));
            die(json_encode(array("sscrp_saved"=>false)));
        }
    }
}

// catch the save request just after wp is loaded
add_action('wp_loaded', 'sscrp_catch_save_share_count_request');

?>

When you have your plugin, we can edit // do something with it lines in your JavaScript file:

  1. For how_many_tweets() it will be:

    $.ajax({
        url: "http://yourdomain.com/path_to_your_wp_installation/?_save_share_count_request=1&type=twitter&value=" + tweets_count + "&post_id=" + post_id,
        dataType: 'json',
        success: function(data) {
            var saved = data.sscrp_saved;
            if(saved) {
                // done!
            } else {
                // oh crap, an error occured
            }
        }
    });
    
  2. For how_many_fb_shares() copy/paste the code from how_many_tweets() and just change:

    ...
        url: "... &type=facebook ...
    ...
    
  3. For how_many_google_pluses() do the same as with facebook:

    ...
        url: "... &type=googleplus ...
    ...
    

Then, you have to somehow filter your posts using $type and $count which you have written to your $wpdb.


I have to go now. I've provided you with more than just a simple information about connecting to Facebook's, Twitter's and Google's APIs. I hope you will make use of it and achieve what you want to achieve.

like image 169
akashivskyy Avatar answered Oct 19 '22 05:10

akashivskyy