Created
November 23, 2012 05:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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