Sorting Posts by Facebook Likes – How to Tutorial – Parts 1-6 Summarized

The Birth of the Idea

This is the final post for a long research project I had recently. My friend wanted to create a writing site at www.thefrankenstoryproject.com. The site was meant to be a creative writing outlet for stories about personal fears. As part of the project he thought it would be nice to sort the stories based on Facebook likes / shares.

Knowing very little about the idea I did some initial research and found that one person had in fact pulled it off. Peter Benting’s post How to order posts by number of Facebook likes accomplished the task but it looks a little dated and didn’t exactly fit what I wanted. However, it did let me know it was possible, gave me a few ideas on how to do it. For that I appreciate his post.

The Specs: What is Being Utilized in this Project

  1. Studiopress’s Minimum Pro WordPress Theme
  2. Facebook’s Javascript SDK
  3. Facebook’s Like Button API
  4. Facebook Query Language(FQL)
  5. HTML / CSS

If some of these topics seem intimidating then you could go back through my research write-ups listed below and see a bit more explanation. I will not be doing anything in-depth in this write-up. Instead this post will go through the process step by step. Feel free to go back for further explanation and make any suggestions in a comment if there is something I missed or something you can add to.

Previous Research Write-Ups

  1. Sorting Posts by Facebook Likes – Part 1 – The Plan
  2. Sorting Posts by Facebook Likes – Part 2 – Using Metadata to Store Facebook Likes
  3. Sorting Posts by Facebook Likes – Part 3 – Learn About Using Facebook’s Like Button API for Individual Posts
  4. Sorting Posts by Facebook Likes – Part 4 – Using the Genesis Loop to Output a Custom Query and Posts with Individual Facebook Like Buttons
  5. More on Facebook’s APIs – Part 5
  6. Connecting to Facebook Using Their APIs – Part 6

Ok so with all the intro stuff out of the way let’s walk through step by step how to get the number of likes / shares from facebook and use this info to order a WordPress query(wordpress posts).

Here is what is covered:

  1. Put Facebook’s Like Button in Posts
  2. Setup Metadata in WordPress for FB’s Likes and Sort Our Posts
  3. Use FB’s Javascript SDK to Capture Likes on Our Site
  4. Connect with FB Daily to “Clean Up” the Number of Facebook Likes and Shares
  5. Finishing Touches: Setup an Automatic Cron Job to Run the Script and Make a Plug-in to Monitor Everything

Firstly since Facebook’s APIs(application programming interfaces) or the way the like button is used may have changed since this post was published, it is recommended that you tread lightly. Should you run into complications perhaps checking Facebook’s current situation might be first on things to check. Regardless reading on Facebook’s Developer Home will do nothing but further your knowledge in that area.

1. Put Facebook’s Like Button in Posts

When I completed this project I used XFBML version of the like button. This means the like button is initialized on my page using their markup language known as XFBML. There are other options. I am not sure on the advantages or disadvantages of those but you are welcome to explore them if that is something that concerns you.

So you go to the like button home and use their widget to get the code. It doesn’t really matter what URL you put in their widget which spits out the like button code you will copy. It doesn’t matter because later we are going to dynamically change the url to the posts on our site. Other settings are up to you.

get-FB-like-button-code

With Facebook’s like button code in hand we can now insert it for our posts.

Since we are using Studiopress’s Minimum Pro WordPress Theme we need to hook into their posts and insert the markup for Facebook’s like button. Other themes will probably have similar ways to hook into this.

Using a filter we can hook into the posts and put the like button code given by Facebook in a nice place near the comments…

facebook-button-for-post

I put my filter in the functions.php file and voila!! The filter is listed below with some comments:

add_filter( 'genesis_post_info', 'post_info_filter' );
function post_info_filter( $post_info ) {
	//* gets the pretty permalink to add to each like button and removes the 'http://'
	$permalinkToadd = substr(post_permalink($post_ID),7);
	//* this next bit takes out the url at the beginning and only returns the pretty permalink part
	//* In this example: substr(post_permalink($post_ID),7) [ABOVE] originally returns thefrankenstoryproject.com/2013/08/image-aligned-left/446/
	//* The strstr cuts off the url at the beginning
	//* This is important because I found the button would not properly initialize without having something in the href of the XFBML first.... Thus I
	//* put in the url and then tack onto the end of it with the variable $permalinkToadd
	$permalinkToadd = strstr($permalinkToadd, '/');
	return $post_info.'<span class="facebook-like-spacer">&nbsp;</span><span class="facebook-like"><fb:like href="http://www.thefrankenstoryproject.com'.$permalinkToadd.'" width="450" style="overflow: visible;" layout="button_count" show_faces="false" send="true"></fb:like></span>';
}

Here’s the simplest version of the filter code from above… no comments and just a few lines…. I would put this in your functions.php file if you understand the code above and don’t need the comments. Make sure to change the url to yours.

add_filter( 'genesis_post_info', 'post_info_filter' );
function post_info_filter( $post_info ) {
	$permalinkToadd = strstr(substr(post_permalink($post_ID),7), '/');
	return $post_info.'<span class="facebook-like-spacer">&nbsp;</span><span class="facebook-like"><fb:like href="http://www.thefrankenstoryproject.com'.$permalinkToadd.'" width="450" style="overflow: visible;" layout="button_count" show_faces="false" send="true"></fb:like></span>';
}

We also need to include another div which the like button code requires. It is a div. Again I use the functions.php file and place the following code in there:

add_action( 'genesis_before', 'insertFBtag' );
function insertFBtag() {printf('<div id="fb-root"></div>');}

Using Studiopress’s hook this will place the div right after the opening body tag before the loop begins. I have heard some arguments about where the div above needs to be placed but this positioning works for me.

Warning: Comment box for like button might get cut off
If you choose to include the comment feature of the like button you may encounter an issue I had. The comment box kept getting cut off and I was forced to use css to get it to display properly. Below you can see the problem…
comment-box-cutoff

I fixed this with the css below which I added to style.css:

.facebook-like{width:450px;}
.facebook-like iframe {
    max-width: inherit;
    position:absolute;
z-index:98;
}

2. Setup Metadata in WordPress for FB’s Likes and Sort Our Posts

With the buttons on the site working correctly with Facebook I then needed a way to store the likes on my side in our database. There is one main reason for this, at the time of this project querying FB was limited and so I needed to get all the likes for every url. It is a bit more extensive than I would have liked but the only solution I could do.

Anyway, we need to setup metadata for each post. Metadata in wordpress is basically a custom field for posts. Perhaps you can use this table for pages too, not sure though. This is where we will store the number of likes.

I set up an action below:

add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
	add_post_meta($post_ID, '_fb_count', '0', true);
	}
}

Now when posts are added this field will be added. If you have old posts without the field then the metadata will be added when you update it.

Now we can use that field in our query to sort our posts.

Using Studiopress’s Minimum Pro WordPress Theme we can use the code below to create a custom query. Add it to the bottom of the front-page.php just before genesis();. Other themes will probably have something similar to create queries for their posts:

/** Replace the standard loop with our custom loop */
function child_do_custom_loop() {
 	genesis_custom_loop( array(
			'meta_key' => '_fb_count',
			'orderby' => '_fb_count',
			'order' => 'DESC'
		) );
}

//* Run the Genesis loop
genesis();

Above this code we need to hook up the genesis_custom_loop. To do so we remove the other loop and hook up our genesis_custom_loop….

/** Replace the standard loop with our custom loop */
		remove_action( 'genesis_loop', 'genesis_do_loop' );
		add_action( 'genesis_loop', 'child_do_custom_loop' );

You may need to search around to figure out where this code is but it is not that big of a file so hopefully it’s not too hard. Done…

We now have the Facebook like button on our posts, a place(metadata) to store that info on our database, and a sorted query in our Studiopress Minimum Pro WordPress Theme to display those posts.

Next we need to start collecting the information from the like button to store it in the metadata we created for our posts.

3. Use FB’s Javascript SDK to Capture Likes on Our Site

This is part of my tutorial because it was initially all I thought I needed to keep track of the likes. I quickly realized that using javascript and facebook’s JDK is great but it will only collect clicks on our site. What if someone clicks a like or share on Facebook itself? We would miss that information.

However, this has been worked into the solution because I did get it working and it helps to make the solution as complete and up-to-date as it can be. That said you could just call FB and not worry about this step. Totally up to you.

Bascially looking at the overall code and what it accomplishes, here is what is happening:
how-i-want-to-connect-to-facebook

So the likes are going to be updated daily using a php script but in the interim the javascript will capture all the clicks on our site instantaneously. Thus our Facebook like count in our database will only miss clicks on Facebook during the day. Then at the end of the day all the counts will be updated up to their current value and the process starts all over again. If you needed more up-to-date information then you could always make more calls to FB throughout the day. Therefore you could adjust the cron job we will use in step five.

Ok with that intro out of the way let’s pop in the javascript….

First, I will load the script on my functions.php page using the wordpress wp_enqueue_script function. This is the safest way to do this and makes it clean.

/** Loads Javascript to capture like clicks on the site */
wp_enqueue_script( 'facebook-like-catch', get_bloginfo( 'stylesheet_directory' ) . '/js/facebook-like-catch.js', array( 'jquery' ), '1.0.0' );

The next step is the actual javascript code that will fire when the like buttons are clicked on our page. Above I named this file facebook-like-catch.js so I will put the following code into a file with that same name.

window.fbAsyncInit = function() {
// Be sure to change the appID to yours
FB.init({appId: 'your-app-ID', status: true, cookie: true, xfbml: true});
// This will fire when a user likes something
FB.Event.subscribe("edge.create", function(href) {
		// setup the ajax request to add facebook like to our count
                jQuery.ajax({
                    url: "/includes/updateData.php",
                    data: {postID: GetPostID(href),action: "add"},
                    dataType: 'json'
                });
    });
// This will fire when a user unlikes something
FB.Event.subscribe("edge.remove", function(href) {
      			jQuery.ajax({
                    url: "/includes/updateData.php",
                    data: {postID: GetPostID(href),action: "del"},
                    dataType: 'json'
                });
    });
  };
// This pulls out the post ID from the pretty permalinks
// we need the ID to update our like count in our database
// Now our permalinks are setup like: /2013/08/image-aligned-left/446/
// so it is /year/month/post title/post id/
	function GetPostID (url){
		//Get Post ID from URL
		var post_ID = new String(url);
		var url_length = post_ID.length;
		post_ID = post_ID.substring(0, (url_length-1));
		post_ID = post_ID.substring(post_ID.lastIndexOf("/")+1, (url_length));
		return post_ID;
	}

  // Load the SDK asynchronously
  (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_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

So there is a lot going on in this script.. It is further explained in another post:

Facebook’s APIs: Javascript, etc.

Basically the functions fire when the like buttons are liked or unliked and then we use JSON to update our database. Thus there is an ajax call:

jQuery.ajax({
                    url: "/includes/updateData.php",
                    data: {postID: GetPostID(href),action: "del"},
                    dataType: 'json'
                });

All the updating is done in the updateData.php file. It looks like:

<?php
// This ID parameter is sent by our javascript client.
$postID = $_GET['postID'];
$action = $_GET['action'];
  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------
  include 'DB.php';

  if($con = @mysql_connect($host, $user, $pass)){
        //set to utf8 encoding
        mysql_set_charset('utf8',$con);
  }
  $dbs = mysql_select_db($databaseName, $con);

  //--------------------------------------------------------------------------
  // 2) Choose proper MySQL Statement and Update data
  //--------------------------------------------------------------------------
  	switch ($action)
	{
	case "add":
	  $result = mysql_query("UPDATE $facebook_likes_TableName SET meta_value = meta_value + 1 WHERE post_id = $postID and meta_key = '_fb_count'");
	  break;
	case "del":
	  $result = mysql_query("UPDATE $facebook_likes_TableName SET meta_value = meta_value - 1 WHERE post_id = $postID and meta_key = '_fb_count'");
	  break;
	default:
	  exit("Error: No action defined...");
	}
	mysql_query( $result, $con );
?>

The above code calls on another file with our database information. The file is named DB.php. You would need to fill in your info in this file to get it working.

<?php

//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "your_username";
$pass = "your_password";

$databaseName = "your_DB_name";
// This is the table where the metadata(FB likes count) is stored
$facebook_likes_TableName = "wp_postmeta";
?>

That is it in a nutshell but there is a lot going on… Comment if I missed anything.

4. Connect with FB Daily to “Clean Up” the Number of Facebook Likes and Shares

This section is covered well in the following post:

Daily Update PHP Script for Facebook Likes

It is also very involved so if you have any questions don’t hesitate to chime in through comments.

Cruise over there to read up on that….

5. Finishing Touches: Setup an Automatic Cron Job to Run the Script and Make a Plug-in to Monitor Everything

With all that working we now need to clean it up a bit and make it convenient. We can set up a cron job to run the script in step 4 everyday for us!!! That is convenient….

I use Arvixe for hosting so here is a post about how to use cron jobs with them. Check it out:

Setting up a Cron Jobs Task with Arvixe Hosting

Finally it would be nice to make sure this is happening everyday and perhaps check out the data/situation when we liked. This can be accomplished with a plugin. We can create a simple plugin to view the results of the cron job. If you read up on step 4 above where we connect and get info from FB, then you will notice at the end of that script a text file is made detailing what changes were made, times, etc. Some basic info about the time of the last update is also stored in a database so we can keep track of that.

Ok so making a simple plugin is not hard. From what I gather WordPress identifies our plugins by the location or directory we place them in and a comment tag… Not sure if the comment tag is completely necessary but I believe it might be. Anyway, go to where you installed wordpress and the plugins reside in the /wp-content/plugins/your-plugins-name/

Therefore, you could just ftp a folder containing your file up to this spot. So your folder will be in the plugins folder.

Our plugin lives here: /wp-content/plugins/FB-like-admin-plugin/

The file is called FB-like-admin-plugin.php

Our plugin will simply list the date/time of the last update in a table and then provide a link to the text file we created when we made the update. Remember the text file has more info in it like what was updated, the differences between our dataset and facebook’s, etc.

Here is what the plugin looks like in it’s final state from the admin page:

fb-like-plugin-admin-view

Nothing too exciting but it does allow us to view our files more conveniently without having to open up an ftp client. Also, more importantly it allows my friend to view them who the project was made for.

If you click on a log file it tells facebook’s data, our current data, and the differences between the two. This was used in testing the script as well. Log files look something like:

log-file

But… Where is the real meat and potatoes right? Where’s the script for the plugin?

Here it is:

<?php
/*
Plugin Name: Facebook Like Update Summary
Plugin URI: http://www.your-domain.com/wp-content/plugins/FB-like-admin-plugin/
Description: This plugin shows the results of a daily update that synchronizes our Facebook like count with Facebook's data
Version: 0.1
Author: Travis Landers
Author URI: http://www.travlanders.com
*/ 

function facebook_like_count_update_page () {
?>
<div class=”wrap”>
<h2>Facebook Like Count Update Summary</h2>
<table width="95%" border="1" cellpadding="2">
<?php
$host = "localhost";
$user = "your-username";
$pass = "your-password";

$databaseName = "your_database";
$facebook_likes_log = "your-table-to-hold-update-info";
//Establish a connection to the DB
	if($con = @mysql_connect($host, $user, $pass)){         
		//set to utf8 encoding
		mysql_set_charset('utf8',$con);
	}
	$dbs = mysql_select_db($databaseName, $con);
	$result = mysql_query("SELECT * FROM $facebook_likes_log ORDER BY DATE DESC");          //query
  while($obj = mysql_fetch_assoc($result)) {
	echo '<tr><th scope="row">'.date("D  -  F j, Y  -  H:i:s",strtotime($obj["date"])).'</th><td><pre><a href="http://www.yourdomain.com/wp-content/plugins/FB-like-admin-plugin/backup-logs/'.$obj["log_file"].'.txt" target="_blank">View Log File</pre></td></tr>';
	}
?>
</table>
</div>
<?php
}

//This adds the menu item for the admin sidebar
function wps_poll_menu () {
add_menu_page('Facebook Like Count Update Summary','FB Like Update','manage_options','wps_poll_admin', facebook_like_count_update_page);
}

add_action('admin_menu','wps_poll_menu');
?>

Conclusions

There is certainly a lot going on with this solution. There are many different things interacting and that makes it tough. Make sure you take it slow, step by step and if you need help just comment and I will try my best.

Sorting Posts by Facebook Likes – Part 3 – Learn About Using Facebook’s Like Button API for Individual Posts

Learn About Using Facebook’s Like Button API for Individual Posts

In case you just landed here… I will briefly recap…. I am trying to store the number of Facebook likes for each post on a site I am helping my friend with. The ultimate goal is to sort the posts by the number of Facebook likes. The site is running a Genesis Framework theme called Minimum Pro. This framework and theme are produced by Studiopress. Back in Sorting Posts by Facebook Likes – Part 1 – The Plan I outline my basic plan.

After that I studied up a bit on metadata and how I could store the number of Facebook likes in my MySQL database. This is outlined at: Sorting Posts by Facebook Likes – Part 2 – Using Metadata to Store Facebook Likes

Which leads us to the next step… Understanding how the Facebook Like button works…. What’s this like button all about anyway?

Interacting with Facebook

This is my first try at getting info from Facebook so I am a bit excited and intrigued. Will it be smooth? I head to the Developers site for Facebook to poke around.

What I want to do is compare how links appear on Jeff Bending’s example with what Facebook is spraying on their site. I also want to learn a bit about the Facebook API. Again if you are joining late in the show then you should know that I am cruising through an example that was presented so kindly by Jeff Bending in his post “How to order posts by number of Facebook Likes“.

Ok so first let’s take a peek at the example link he has in his example:

<div class="fb_like_div">
  <iframe src="http://www.facebook.com/widgets/like.php?href=http://hisurl.com?p=38&amp;layout=button_count&amp;show_faces=false&amp;width=95&amp;action=like&amp;font&amp;colorscheme=light&amp;height=20&amp;locale=en_US" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:95px; height:24px;" allowTransparency="true"></iframe>
  </div>

So I guess one mystifying thing is how he got this iframe into his <div class=”fb_like_div”>. He kind of skipped explaining this step. This is the whole reason I felt like writing my own post about this. I am not sure but at first guess I would think I can either inject it with jquery or perhaps in the loop put that output into the posts.

I dig deeper into his example page and I see that he also loaded a script of some sort from Facebook… Hmmm…..

<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

So I can see what he is working with and now I can continue on…

Continuing My Safari Through Facebook

As I continue my learning adventure through Facebook it becomes quite apparent that I need to learn a thing or two about the Graph API. As Facebook puts it:

The Graph API is the primary way that data is retrieved or posted to Facebook.

This is definitely some interesting stuff and a good overview of how things are working but I need to hone in on my goal. I take a look at: The Facebook Developer Page for The Like Button

This page has some definite gold… and I am getting much closer to understanding what is going on. As I read through this page I see that currently:

There are three ways to implement the Like button: using HTML5, XFBML (a special Facebook markup) and iframe.

I guess Peter must be using XFBML to get his like button into his page. Although the reading on Facebook and his example don’t seem to line up perfectly. I dig a little deeper and find that other people have tried to put many Facebook like buttons on the same page. It seems many people would like to have multiple Facebook Like buttons that each work independently and each reference an individual post. Great, more information!!

Wojciech Kosinski on his blog gives a brief overview in his post: “Multiple dynamic Facebook like buttons on one page“. If you skim through this article it looks different from Peter’s example too… Hmmm…. What is going on here?

Well, one person who read Wojciech Kosinski’s blog commented on the likely culprit. It’s facebook!!! They said:

This post has been written about a year and a half ago. Since then Facebook has changed the like button code at least a few times. The code may differ now from what it was at a time of writing this blog post.
Always use Like button code from facebook documentation.

Ok… Great idea…. So perhaps Wojciech Kosinski’s post is outdated and also Peter’s technique is a bit different but I can still learn from them. It has my mind in the right area now. Here is what I need to do with this XFBML….

  1. Inject facebook’s special markup (XFBML)… something like this:
    <fb:like href="http://example.com" width="450" layout="button_count" show_faces="true" send="true"></fb:like> 
  2. Next, their javascript will initialize all those buttons

Here is what the current setup looks like if you cruise over to The Facebook Developer Page for The Like Button. When you click get code and select the XFBML option you get a screen that looks something like below:
facebook-likes-xfbml

Is this the best option?? I really don’t know at this point. Since there is a lot of talk about switching over the HTML5 I am tempted to try that option but I think I will use the XFBML option for now since I don’t know the difference.(chime in if you can eleborate on the differences, please..)

Also, this could be outdated by the time you read my blog post so make sure you use the most current FB code by looking on their developer’s website.(i.e.- The Facebook Developer Page for The Like Button)

Success!!! I have wrapped my head around the idea and I am ready to move on to the next step!!! Now that I understand how the Facebook Like button is working I just need to get my loop code in Genesis to spit those buttons out!!!

…NEXT…

Sorting Posts by Facebook Likes [Part 4] – Using the Genesis Loop to Output a Custom Query and Posts with Individual Facebook Like Buttons (That’s a mouthful!!!)

Sorting Posts by Facebook Likes – Part 1 – The Plan

In my attempt to help out a buddy, (actually he helped me with some graphics), so in my attempt to complete a trade with a buddy I am working on Studiopress’s Minimum Pro theme and my friend wants to have his posts listed by Facebook likes.

The plan is to have Facebook likes for the stories(posts) that will be on the site. Users will create their own stories and then others can use the Facebook like button to vote on them. Then the stories will be listed in order by Facebook likes.

This doesn’t seem impossible since Peter Benting already seems to have done it. Check out his post entitled “How to order posts by number of Facebook likes“.

The bad thing is that it seems possible but his post is beyond my comprehension at this point. Meaning I need to read up and get things figured out here. I want to learn something. I need a simpler approach that I understand. Not just copying and pasting.

Therefore, this 6 part documentation of my project details the exploration I took in getting to my final solution. It started out as a 3 part thing that has ballooned into 6 parts. If you are interesting in learning in any of the many small intricate pieces to this puzzle then explore any of the 6 steps I have documented. If you are only interested in the final solution then check that out…(when I post it)

Where to start? Since this will be a multi-step solution I will try to outline the different parts here and then have individual blog posts about each step. The way I see the problem is that I need to accomplish these things:

  1. Learn About Metadata, What is it? Etc.
    • This is where Peter stored the number of facebook likes and ultimately uses it to sort his results. Seems like this is pretty important to understand. Check out the write-up here.
  2. Learn About Facebook’s Like Button
  3. Using the Genesis Loop to Output a Custom Query and Posts with Individual Facebook Like Buttons
    • This addresses how to work with Studiopress’s Minimum Pro theme and how to place the Facebook API code with a loop. I also talk about a problem I had with getting the Facebook comment box to display properly. The pesky thing kept getting cut off.
  4. More on Facebook’s APIs and How they fit into my Project
    • This talks more about Facebook’s APIs and how to use them. Specifically I used FQL(Facebook Query Language) and their javascript SDK to accomplish what I wanted. This was a huge time monster in my project because I knew very little about Facebook APIs(application programming interfaces) and I didn’t find great examples when I looked around.

That’s it… Pretty easy, right???? Examine the six posts above and see how I did it. On the other hand, you could just check out my final post about the project which is my attempt to summarize this massive undertaking. Don’t get me wrong this would not be massive if you already know about PHP, WordPress, Studiopress’s Minimum Pro theme, Cron Jobs, Facebook’s APIs, and a few other things I had to get a handle on for the first time.

Anyway, hope this helps someone who may desire to use information from Facebook to manipulate their site.