2016-02-25 2 views
2

Привет, У меня есть многоуровневый wp, где я использую API Transients для кэширования ссылок на социальные сети. Я использую Ответ, размещенный здесь: Caching custom social share count in WordPressНеточное количество данных связано с кэшем API переходного процесса

Все работает, однако это не дает мне точных подсчетов голосов для всех сообщений. У некоторых есть правильное количество акций, которые другие просто показывают, что кажется случайным числом. Например, сообщение, которое имеет 65 facebook, только показывает 1 при добавлении кода Transient. Когда я удаляю Transient, он показывает точное количество акций для всех из них. Любые идеи о том, что может это сделать?

Вот мой код добавлен в functions.php:

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

 

 

 
    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){ 
 
     // Create unique transient key 
 
     $transientKey = 'sc_' + md5($url); 
 

 
     // Check cache 
 
     $cache = get_site_transient($transientKey); 
 
     
 
    \t if($cache) { 
 
      return $cache; 
 
     } 
 
    \t 
 
    \t else { 
 
    \t 
 
     $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); 
 
     $count = curl_exec($ch); 
 
     if(curl_error($ch)) 
 
     { 
 
      die(curl_error($ch)); 
 
     } 
 

 
     // Cache results for 1 hour 
 
     set_site_transient($transientKey, $count, 60 * 60); 
 
     return $count; 
 
    \t 
 
    } 
 

 
    } 
 

 

 
    }

Everything works if I remove if($cache) { 
     return $cache; 
    } 

но страница очень медленно.

Я потратил часы, пытаясь понять это, поэтому подумал, что я попрошу экспертов. Я прикрепил скриншот, сравнивая количество почтовых сообщений с API Transient и без него, чтобы вы могли видеть различия.

Comparison of Share Counts

Благодаря

+0

Привет Даниэль, сделал вам удалось найти решение с помощью переходных? –

ответ

0

Я использовал этот фрагмент и он сделал работу за sharecount апи

function aesop_share_count(){ 

    $post_id = get_the_ID(); 

    //$url = 'http://nickhaskins.co'; // this one used for testing to return a working result 

    $url = get_permalink(); 

    $apiurl = sprintf('http://api.sharedcount.com/?url=%s',$url); 

    $transientKey = 'AesopShareCounts'. (int) $post_id; 

    $cached = get_transient($transientKey); 

    if (false !== $cached) { 
     return $cached; 
    } 

    $fetch = wp_remote_get($apiurl, array('sslverify'=>false)); 
    $remote = wp_remote_retrieve_body($fetch); 

    if(!is_wp_error($remote)) { 
     $count = json_decode($remote,true); 
    } 

    $twitter  = $count['Twitter']; 
    $fb_like = $count['Facebook']['like_count']; 

    $total = $fb_like + $twitter; 
    $out = sprintf('%s',$total); 

    set_transient($transientKey, $out, 600); 

    return $out; 
} 
Смежные вопросы