// get Facebook shares // call function in wordpress with default values // echo getFBCount(get_the_ID(), 'share', 24); // possible $counter values: share, like, comment, total, click // $cachetime: time to cache the data in hours function getFBCount($postid, $counter = 'share', $cachetime = 24) { // check if $postid and $cachetime is int if (!is_int($postid) || !is_int($cachetime) || $cachetime < 1) { return 'values are not numeric'; } // get permalink with postid $link = get_permalink($postid); // create post_meta name $countername = sprintf("_fbcount%s", $counter); // get cached data, if available $cacheddata = get_post_meta($postid, $countername, true); // if no cached data available or data is older than 24 hours, refresh/get data from facebook if(!empty($cacheddata) && $cacheddata['timestamp'] + (60 * 60 * $cachetime) > time() ) { $count = $cacheddata['count']; } else { $url = sprintf("http://api.facebook.com/restserver.php?method=links.getStats&urls=%s", $link); $request = new WP_Http; $result = $request->request($url); $xml = simplexml_load_string($result['body']); switch($counter) { case 'share': $count = (int)$xml->link_stat->share_count; break; case 'like': $count = (int)$xml->link_stat->like_count; break; case 'comment': $count = (int)$xml->link_stat->comment_count; break; case 'total': $count = (int)$xml->link_stat->total_count; break; case 'click': $count = (int)$xml->link_stat->click_count; break; default: return 'not existing counter specified'; break; } if($count !== '' && is_int($count)) { $metadata = array(); $metadata['timestamp'] = time(); $metadata['count'] = $count; update_post_meta($postid, $countername, $metadata); } } return $count; }