它认为您的问题在于您正在将帖子ID作为url参数传递给facebook API:
$url = get_the_ID();
此外,作为
get_posts
返回post对象数组,可以使用以下代码:
$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 );
}
我会更进一步,建议取消对
wp_next_scheduled
在激活操作挂钩中,不需要它,因为在插件激活时,计划的事件应该不存在。最后,我建议使用
wp_remote_get
而不是
file_get_contents
, 我认为这真的更好,对请求有更多的控制:
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:我认为这不是一个很好的方法。获取所有帖子并一个接一个地连接到Facebook,所有这些都在相同的WordPress负载中,可能会非常缓慢和激烈。