Guest User

Untitled

a guest
Mar 18th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. function wnet_get_transient_remote_json($transientname, $url, $interval=1800) {
  2. // those are the same arguments as 'set_transient()'
  3.  
  4. $stalecachename = 'stalecache_' . $transientname;
  5. // we generate a consistent name for the backup data
  6.  
  7. if ( false === ( $json = get_transient($transientname) ) ) {
  8. $response = wp_remote_get($url);
  9. // get the remote data as before, but this time...
  10.  
  11. if (is_wp_error($response) || ! isset($response['body']) || 200 != $response['response']['code']) {
  12. // check to see all of the ways that the data request could return an error.
  13.  
  14. $json = get_option($stalecachename);
  15. // one of our checks failed, so we get the stale cache data from WP Options and store in the $json variable.
  16.  
  17. } else {
  18. $json = $response['body'];
  19. // no errors! we store the remote data in the $json variable.
  20.  
  21. if (! get_option($stalecachename)) {
  22. add_option($stalecachename, $json, '', 'no');
  23. // Store the data in the $json variable in the options table as a backup.
  24. // We _could_ have just used update_option(), but by using add_option() with 'no' in the third arg
  25. // we keep the option from being 'autoloaded' into memory and reducing memory usage.
  26. } else {
  27. update_option($stalecachename, $json);
  28. // update_option() preserves the 'autoload' setting of a previously created option.
  29. }
  30. }
  31.  
  32. set_transient($transientname, $json, $interval );
  33. // Regardless of whether we got the data from the remote site or our local backup, we store that data in the transient.
  34. // We won't try to regenerate that data until the transient expires.
  35.  
  36. }
  37. return $json;
  38. // on general principle return the data we are storing in case we'd like to do something with it.
  39. }
  40. }
Add Comment
Please, Sign In to add comment