Skip to content

Instantly share code, notes, and snippets.

@cjanis
Created November 23, 2012 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjanis/4134087 to your computer and use it in GitHub Desktop.
Save cjanis/4134087 to your computer and use it in GitHub Desktop.
Using Facebook's Social Graph to Find A WordPress Blog's Most Popular Posts
<?php
// this goes into your theme's functions.php file
function popularPosts($limit) {
global $wpdb;
$posts = $wpdb->get_results("SELECT * FROM wp_posts WHERE $wpdb->posts.post_status='publish' AND $wpdb->posts.post_type='post'");
// get data for each post
$popular = array();
foreach ($posts as $post) {
setup_postdata($post);
$info = array();
$info["id"] = $post->ID;
$info["title"] = $post->post_title;
$info["url"] = get_permalink($info["id"]);
$info["excerpt"] = $post->post_excerpt;
$info["shares"] = json_decode(file_get_contents("http://graph.facebook.com/".$info["url"]))->{"shares"};
$popular[$info["shares"]] = $info;
}
// sort posts by number of shares
function sortByOneKey(array $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
} else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
$popular = sortByOneKey($popular, "shares", false);
// prepare a list of the most popular posts
$i = 0;
foreach ($popular as $post) {
if(++$i > $limit) break;
echo '<div class="excerpt"><a href="'.$post["url"].'">'.$post["title"].'</a>: '.$post["excerpt"].'</div>'; // modify this to suit your theme's needs
}
}
?>
<?php
// this goes into your theme wherever you want the list of popular posts to go, change the number to modify how many posts are shown
echo popularPosts(5)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment