0

I am new to PHP generally and caching and am trying to develop a Facebook share counter for Wordpress. As advised by a member here, since it's not optimum to make calls to the API and slow down the website each time, I decided to cache the results and went with the static method. Here's the code I am using.

function fb_cache($atts) {
    $url = $atts['url'];
    static $fb_cache = array();
    if (isset($fb_cache[$url])) {
    $fb_count = $fb_cache[$url];
    return $fb_count;   
    } else {
    $fb = json_decode( file_get_contents('http://graph.facebook.com/' . $url) );
    $fb_count = $fb->share->share_count; 
    $fb_cache[$url] = $fb_count;
    return $fb_count;
    }
}

This doesn't seem to work as the number keeps changing every few seconds and the API calls are thus being made each time. To use it as a plugin, I also have an instantiating code in the end.

static function get_instance() {
    static $instance = false;

    if ( ! $instance ) {
        $instance = new self;
    }

}

Can someone tell me what I am doing wrong. I apologize if it's a noob question and if I am using the wrong method altogether.

5
  • what type of cache do you use? Commented Apr 20, 2018 at 5:26
  • static I guess. I am totally new to this. Did a lot of reading and since I am on xampp right now and plan on getting a shared hosting, i am trying to keep it as simple as possible Commented Apr 20, 2018 at 5:30
  • define static cache .. Commented Apr 20, 2018 at 5:31
  • When you assign a variable a static value for some time so that it doesnt make calls to the db or in this case the funcction to make api calls each time the website or a page loads. Commented Apr 20, 2018 at 5:36
  • Thanks for all the help everyone. I found caching to text files the best option for me right now. If it seems to slow down the website in the future I am gonna try caching to a DB. Thanks for the advice @madalinivascu Commented Apr 21, 2018 at 5:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.