I recently developed a news blog, and my client needs facebook share count. I Successfully able to get the share count and update the custom field using below code.(with the help of cybermeta). What this code does is, it loops through all the available posts and gets the share count from facebook api and updates the individual post's custom field.
register_activation_hook( __FILE__, 'cb_fb_share_count_activation' );
function cb_fb_share_count_activation() {
wp_schedule_event( time(), 'hourly', 'cb_update_fb_share_count' );
}
register_deactivation_hook( __FILE__, 'cb_delete_fb_share_count_schedule' );
function cb_delete_fb_share_count_schedule() {
wp_clear_scheduled_hook( 'cb_update_fb_share_count' );
}
add_action( 'cb_update_fb_share_count', 'cb_update_count' );
function cb_update_count(){
$posts = get_posts(array('numberposts' => -1) );
foreach($posts as $post) {
$url = get_permalink( $post->ID );
$response = wp_remote_get('https://api.facebook.com/method/links.getStats?urls='.$url.'&format=json' );
if( ! is_wp_error( $response ) ) {
$fbcount = json_decode( wp_remote_retrieve_body( $response ) );
$fb_share_count = $fbcount[0]->share_count;
update_post_meta( $post->ID, 'cb_fb_share_count', $fb_share_count );
} else {
//Do something if it was an error comunicating with Facebook
}
}
}
However, It does'nt seem to be a good way to get share count and updating custom field.
Is there any better approch? I don't want any problem even if the blog has 2000 articles in the long run.