如何在 WordPress 中顯示 Twitter 追隨者數量及更多資訊

WPressize Me

12/04/2022

如何在 WordPress 中顯示 Twitter 追隨者數量及更多資訊

最後更新於 2013 年 6 月 14 日 | 編輯部 | 審查者:Syed Balkhi

我們之前寫過一個可以顯示 Twitter 追隨者數量的程式碼,由 Rarst 貢獻。在這篇文章中,我們會分享一個更進階且更優雅的程式碼,讓你能夠在 WordPress 中顯示 Twitter 追隨者數量。這段程式碼同樣由 Rarst 貢獻。

功能

此功能不僅限於顯示追隨者數量,還可以抓取 Twitter 用户/顯示 API 方法所返回的任何非嵌套值。

它具有兩級快取機制:

  • 查詢值會以陣列形式儲存在資料庫中,使用 WP 選項設定為 $interval 秒;
  • API 響應會儲存於記憶體中,讓你能夠查詢任何數量的字段,而不會生成多餘的 API 請求。

這應該可以安全地同時用於多個值和多個用户,而不必擔心耗盡 API 限制。

教程

首先打開你的主題的 functions.php 文件,並添加以下程式碼:

function rarst_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 update
if ( !isset( $cache[$username][$field] ) ) {
$cache[$username][$field] = NULL;
$cache[$username]['lastcheck'] = 0;
}

// if outdated
if( $cache[$username]['lastcheck'] < (time()-$interval) ) {

// holds decoded JSON data in memory
static $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 requested
foreach ($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];
}

完成程式碼插入後,你現在可以在任何 WordPress 模板文件中使用這段程式碼。簡單地插入以下程式碼:

echo rarst_twitter_user('wpressize-me', 'name').' has '.
rarst_twitter_user('wpressize-me', 'followers_count').' followers after '.
rarst_twitter_user('wpressize-me', 'statuses_count').' updates.';

上面的程式碼會顯示如下內容:

WPBeginner 擁有 5846 位追隨者,發布了 1300 條更新。

來源: Rarst



Related Posts

  • 2025-02-16
  • WordPress 教学

你是否想过,能不能用更引人注目的方式取代WooCommerce中基本的促销徽章?答案是肯定的!通过自定义产品徽章,你可以在在线商店中突出新产品、折扣商品或限时优惠。在这篇文章中,我们将展示给你两个简单的方法,使用强大的插件或添加简单代码来为你的WooCommerce商店添加自定义产品徽章。

閱讀更多
  • 2025-01-18
  • WordPress 教学

我们都知道推荐计划是强大的武器。但要找到真正的品牌代言者并不容易。许多计划吸引的只是想快速赚钱的人,导致非真实的推广,无法有效转化客户。幸好,作为 WooCommerce 商店的店主,您有一个巨大的优势:一群真正喜爱和使用您产品的内置客户群。通过将这些现有客户转化为推广合伙人,您可以释放真实口碑营销的力量。

閱讀更多
  • 2025-01-10
  • WordPress 教学

最近,我们的一位比利时读者在其在线商店中苦于销售增长缓慢。除了其他建议外,我们建议他们在网站上设置Bancontact支付。Bancontact是一种主要在比利时使用的流行支付系统,客户可以通过银行账户进行安全的实时支付。

閱讀更多

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>