Created
August 23, 2016 08:42
-
-
Save maheshwaghmare/619dc6a307d3085a1b70c0fb97336736 to your computer and use it in GitHub Desktop.
WordPress transients example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get a list of email subscribers. | |
* | |
* @return object The HTTP response that comes as a result of a wp_remote_get(). | |
*/ | |
function css_t_subscribers() { | |
// Do we have this information in our transients already? | |
$transient = get_transient( 'css_t_subscribers' ); | |
// Yep! Just return it and we're done. | |
if( ! empty( $transient ) ) { | |
// The function will return here every time after the first time it is run, until the transient expires. | |
return $transient; | |
// Nope! We gotta make a call. | |
} else { | |
// We got this url from the documentation for the remote API. | |
$url = 'https://api.example.com/v4/subscribers'; | |
// We are structuring these args based on the API docs as well. | |
$args = array( | |
'headers' => array( | |
'token' => 'example_token' | |
), | |
); | |
// Call the API. | |
$out = wp_remote_get( $url, $args ); | |
// Save the API response so we don't have to call again until tomorrow. | |
set_transient( 'css_t_subscribers', $out, DAY_IN_SECONDS ); | |
// Return the list of subscribers. The function will return here the first time it is run, and then once again, each time the transient expires. | |
return $out; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment