PHP code example of alleyinteractive / wp-soft-transients

1. Go to this page and download the library: Download alleyinteractive/wp-soft-transients library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alleyinteractive / wp-soft-transients example snippets


use function Alley\WP\Soft_Transients\get_soft_transient;
use function Alley\WP\Soft_Transients\set_soft_transient;

function get_github_orgs_from_api() {
  $request = wp_remote_get( 'https://api.github.com/organizations' );
  if ( is_wp_error( $request ) ) {
    return $request;
  } elseif ( 200 !== wp_remote_retrieve_response_code( $request ) ) {
    return new WP_Error( 'bad_response', 'Bad response from GitHub API', $request );
  }
  $orgs = json_decode( wp_remote_retrieve_body( $request ), true );
  set_soft_transient( 'github_orgs', $orgs, HOUR_IN_SECONDS );
  return $orgs;
}

function get_github_orgs() {
  return get_soft_transient( 'github_orgs' ) ?: get_github_orgs_from_api();
}

function refresh_github_orgs_cron_task( $transient_key ) {
  $response = get_github_orgs_from_api();
  if ( is_wp_error( $response ) ) {
    // If the response is an error, schedule a new cron event. We can schedule this for whenever
    // makes sense for the given service, e.g. one minute from now.
    wp_schedule_single_event( time() + MINUTE_IN_SECONDS, current_action(), [ $transient_key ] );
  }
}
add_action( 'transient_refresh_github_orgs', 'refresh_github_orgs_cron_task' );

// Create the transient object.
$key       = 'my_request_' . md5( serialize( [ $url, $args ] ) );
$transient = ( new Soft_Transient( $key ) )
  ->set_cron_args( [ $url, $args ] )
  ->set_cron_hook( 'my_custom_cron_event' );

// Set a value.
$transient->set( get_remote_data( $url, $args ), HOUR_IN_SECONDS );

// Get a value.
$transient->get();

// Delete a value.
$transient->delete();

// Refresh a value.
add_action(
  'my_custom_cron_event',
  function( $transient_key, $url, $args ) use ( $transient ) {
    $transient = new Soft_Transient( $transient_key );
    $transient->set( get_remote_data( $url, $args ), HOUR_IN_SECONDS );
  },
  10,
  3
);