Home » Wordpress » Including twitter/flickr api calls on every page load (WordPress)

Including twitter/flickr api calls on every page load (WordPress)

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to include my latest flickr photos and twitter status updates in a wordpress sidebar or footer using JSONP requests. The problem is of course each page reload will perform a new ajax call, and I believe the Twitter api has usage limits.

I was considering what cross-browser data persistance options I had with javascript and the best I could think of was cookies.

Would storing the ajax results in a cookie (Setting the expiry to day, I dont update my twitter/Flickr that often). be the best solution for a javascript-based Twitter and Flickr api call?

Thanks

Answers:

The best solution for javascript-based Twitter and Flickr api calls when using WordPress is to use the WordPress Transient API. The Transient API is a persistent cache method built in to WordPress meant to cache items that change frequently. You can set the cache expires time and WordPress will check the database first for the transient if it returns false it will use the json call to return the item.

Here is an example using a transient and shortcodes to store a users most recent tweet. The code below is from Aaron Jorbin Twitter Transients Plugin

function twitter_status($atts){
    extract(shortcode_atts(array(
    'screenname' => '',
    'count' => 1
    ), $atts));
    $transient = "$screenname"."_$count"."_twitter_status";
    $statuses =  get_transient($transient);
    if ($statuses == true  )
    {
        return $statuses;
    }
    elseif ($screenname != false)
    {
        $site = "http://twitter.com/statuses/user_timeline.json?screen_name=$screenname&count=$count";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $site);
        $result = curl_exec($ch);
        $tweets = json_decode($result);
        ob_start();
        foreach ( (array) $tweets as $tweet){
            $tweetcontent = $tweet->text;
            $newcontent = preg_replace('%@([^\s]*)%', "<a href="http://twitter.com/\1">@\1</a>", $tweetcontent);
            echo "<div class="twitter_shortcode"><p>
            <img class="twitter_shortcode_image" src="&quot;.esc_url($tweet-&gt;user-&gt;profile_image_url).&quot;"><span class="twitter_shotcode_username"><a href="http://twitter.com/&quot;.$tweet-&gt;user-&gt;screen_name.&quot;">".$tweet-&gt;user-&gt;screen_name."</a>&nbsp;—&nbsp;</span>$newcontent</p>
            </div>";

        }
        $tweet_display = ob_get_clean();
        set_transient($transient, $tweet_display, 120);
        return $tweet_display;
    }
    else
    {
        return false;
    }
}

add_shortcode('twitter_status', 'twitter_status');