Caching custom social share count in WordPress

2019-05-18 13:24发布

I really like having a share counter on my blogposts. I noticed that it actually encourages visitors to share the content themselves. Because there are no WordPress sharecount plugins out there that I actually find satisfying (most of them make way to much calls), I wrote the code myself.

It works perfect, but still slows down my site. So I would rather it caches and refreshes once per hour or so. I don't know how to manage this though … Any ideas?

This is what I put in the themes function file:

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;
    }

}

And this is what I use in 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 -->

Then I also add some css.

1条回答
叛逆
2楼-- · 2019-05-18 13:59

Like vicente said, you should use the built in transient cache.

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;
}
查看更多
登录 后发表回答