如何在 WordPress 中显示 Twitter 关注者数量及更多

(图1)

我们之前写过一段代码,可以让您显示 Twitter 关注者数量,该代码由Rarst贡献。在本文中,我们将分享一个更高级、更优雅的代码,它可以让您在 WordPress 中显示 Twitter 关注者数量。这个脚本也是由拉斯特贡献的。

特征

此功能不限于关注者数量。它可以获取Twitter users/show API 方法返回的任何非嵌套值。

它有两级缓存:

  • 查询的值使用 WP 选项以数组形式存储在数据库中,持续 $interval 秒;
  • API 响应存储在内存中,因此您可以查询任意数量的字段,而无需生成多个 API 请求。

这应该可以安全地同时用于乘法值和乘法用户,而不必担心耗尽 API 限制。

教程

首先打开主题的functions.php文件并添加以下代码:

functionrarst_twitter_user( $username, $field, $display= false ) {$interval= 3600;$cache= get_option('rarst_twitter_user');$url= 'http://api.twitter.com/1/users/show.json?screen_name='.urlencode($username);if( false == $cache)$cache= array();// if first time request add placeholder and force updateif( !isset( $cache[$username][$field] ) ) {$cache[$username][$field] = NULL;$cache[$username]['lastcheck'] = 0;}// if outdatedif( $cache[$username]['lastcheck'] < (time()-$interval) ) {// holds decoded JSON data in memorystatic$memorycache;if( isset($memorycache[$username]) ) {$data= $memorycache[$username];}else{$result= wp_remote_retrieve_body(wp_remote_request($url));$data= json_decode( $result);if( is_object($data) )$memorycache[$username] = $data;}if( is_object($data) ) {// update all fields, known to be requestedforeach($cache[$username] as$key=> $value)if( isset($data->$key) )$cache[$username][$key] = $data->$key;$cache[$username]['lastcheck'] = time();}else{$cache[$username]['lastcheck'] = time()+60;}update_option( 'rarst_twitter_user', $cache);}if( false != $display)echo$cache[$username][$field];return$cache[$username][$field];}
1、本站目前拥有近 1000+ 精品收费资源,现在加入VIP会员即可全部下载。
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
SEA模板网 » 如何在 WordPress 中显示 Twitter 关注者数量及更多

发表评论

加入本站VIP会员订阅计划,海量资源免费查看

目前为止共有 3654 位优秀的VIP会员加入! 立刻加入VIP会员