我将此代码用于显示共享计数器;
function facebook_share() {
$post_id = get_the_ID();
$url = get_permalink( $post_id );
$response = wp_remote_get( 'http://graph.facebook.com/?id=' . $url );
if( !is_wp_error( $response ) ) {
$json = json_decode( wp_remote_retrieve_body( $response ) );
return isset( $json->shares ) ? $json->shares : 0;
} else {
return 0;
}
}
function googleplus_share() {
$post_id = get_the_ID();
$url = get_permalink( $post_id );
$response = wp_remote_post( 'https://clients6.google.com/rpc', array(
'body' => '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]',
'headers' => array(
'content-type' => 'application/json'
)
));
if( !is_wp_error( $response ) ) {
$json = json_decode( wp_remote_retrieve_body( $response ) );
if( !isset( $json[0]->error ) ) {
return $json[0]->result->metadata->globalCounts->count;
} else {
return 0;
}
} else {
return 0;
}
}
function social_shares() {
$fb = facebook_share();
$google = googleplus_share();
$totalcounts = $fb + $google;
return $totalcounts;
}
但它太慢了,因为总是计算总份额所以我想将总份额数保存为数据库中的 post meta ...然后我会显示总份额的数量来自数据库
感谢答案
答案 0 :(得分:0)
假设这与使用后update_post_meta
https://codex.wordpress.org/Function_Reference/update_post_meta
将你的计数保存在你的函数中的帖子的id中 - 我假设你将通过cron任务等运行...
然后在您的帖子模板上使用get_post_meta
https://developer.wordpress.org/reference/functions/get_post_meta/
显示计数。