It think that your problem is the you are passing the post ID as url parameter to facebook API:
$url = get_the_ID();
Also, as get_posts
return an array of post objects, you could use this code:
$posts = get_posts(array('numberposts' => -1) );
foreach($posts as $post) {
$url = get_permalink( $post->ID );
$fbcount = json_decode( file_get_contents( 'https://api.facebook.com/method/links.getStats?urls=".$url."&format=json' ) );
$fb_share_count = $fbcount[0]->share_count;
update_post_meta( $post->ID, 'cb_fb_share_count', $fb_share_count );
}
I would go further and suggest to remove the checking of wp_next_scheduled
in the activation action hook, it is not needed because at plugin activatition the scheduled event is supposed to not exists. And finally, I suggest to use wp_remote_get
instead of file_get_contents
, I think it is really better and have more control about the request:
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
}
}
}
PD: I think this is no very good approach. Get all posts and connect to Facebook one by one, all in the same WordPress load, can be very slow and intense.