is_wp_error() and handling errors

Im trying to build a function which grabs the feedburner "readers" using wp_remote_get(). I noticed that it frequently returned a value of 0.

I assumed at first that it was a WordPress error (handled by is_wp_error()) or a flaw with wp_remote_get(). Wrong of-course..

Feedburner just kept crashing, so I used a second transient to store a result (never 0) with an expiration of 7 days. The part which i cant get my head around is handling errors with is_wp_error(). I need to force an error so i can handle it properly, before I put it up on production.

Heres an illustration:

$result = wp_remote_get( 'http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=' . urlencode($username) );

if ( is_wp_error($result) )
    return false;

Whats the best way to force an error? Should i use new WP_error()?

Topic transient errors customization Wordpress

Category Web


WordPress can be inconsistent as to when is returns a WP_Error object and when it just returns false or string(0) when actually there was an error. I am not sure exactly what feedburner is returning that is not triggering a WP_Error from wp_remote_get() - but if you know wp_remote_get() will return an WP_Error, I would just set $result = new WP_Error( 'my-error' ); This is the same object that wp_remote_get() will return on error.


To grab Feedburner stats, I've always used wp_cache_get. Here's a function I've had success with

function get_feedburner_stats() {
  $fbrefreshtime = 43200;  //Refresh Feedburner twice in a day

  $fb = wp_cache_get('fbstats_key');

  if ($fb == false) {
    $yourfeeduri = 'YOUR_FEEDBURNER_USERID'; 
    $feed = 'https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$yourfeeduri;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $feed);
    $feed = curl_exec($ch); curl_close($ch);
    $xml = new SimpleXMLElement($feed);
    $fb = $xml->feed->entry['circulation']; 

    //Set the Value in Cache
    wp_cache_set('fbstats_key', strval($fb), '', $fbrefreshtime);
  }
  return $fb;
} 

To return the value, I use this

<?php echo get_feedburner_stats(); ?>

That being said, Feedburner is horribly unreliable. What I'd recommend doing is building in a conditional that if the number = 0, then it returns a static number.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.