【问题标题】:Caching custom social share count in WordPress在 WordPress 中缓存自定义社交共享计数
【发布时间】:2014-09-04 07:49:48
【问题描述】:

我真的很喜欢在我的博文上设置一个分享计数器。我注意到它实际上鼓励访问者自己分享内容。因为没有真正让我满意的 WordPress sharecount 插件(它们中的大多数让位于很多调用),所以我自己编写了代码。

它运行良好,但仍会减慢我的网站速度。所以我宁愿它每小时缓存和刷新一次左右。我不知道如何管理这个……有什么想法吗?

这是我放在主题函数文件中的:

class shareCount {
private $url,$timeout;
function __construct($url,$timeout=10) {
$this->url=rawurlencode($url);
$this->timeout=$timeout;
}

function get_tweets() { 
$json_string = $this->file_get_contents_curl('http://urls.api.twitter.com/1/urls/count.json?url=' . $this->url);
$json = json_decode($json_string, true);
return isset($json['count'])?intval($json['count']):0;
}

function get_fb() {
$json_string = $this->file_get_contents_curl('http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
$json = json_decode($json_string, true);
return isset($json[0]['total_count'])?intval($json[0]['total_count']):0;
}

private function file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$cont = curl_exec($ch);
if(curl_error($ch))
    {
        die(curl_error($ch));
    }
        return $cont;
    }

}

这就是我在 single.php 中使用的:

<!-- Begin mod: Add share counter -->
<span class="share-count">
    <?php 
    $obj=new shareCount(get_permalink( $post->ID ));  
    echo $obj->get_tweets() + $obj->get_fb();
    ?>
</span>
<span class="share-text">
    keer gedeeld
</span>
<!-- End mod: Add share counter -->

然后我还要添加一些css。

【问题讨论】:

标签: php wordpress counter social


【解决方案1】:

就像 vicente 说的,你应该使用内置的瞬态缓存。

private function file_get_contents_curl($url){
    // Create unique transient key
    $transientKey = 'sc_' + md5($url);

    // Check cache
    $cache = get_transient($transientKey); 
    if($cache) {
        return $cache;
    }

    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
    $cont = curl_exec($ch);
    if(curl_error($ch))
    {
        die(curl_error($ch));
    }

    // Cache results for 1 hour
    set_transient($transientKey, $cont, 60*60);

    return $cont;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多