PHP code example of duckdev / wp-cache-helper

1. Go to this page and download the library: Download duckdev/wp-cache-helper 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/ */

    

duckdev / wp-cache-helper example snippets


function do_something() {
    $cache_key = 'some-cache-key';
    $cached    = wp_cache_get( $cache_key );

    // Return the cached value.
    if ( $cached ) {
        return $cached;
    }

    // Do all the work to calculate the value.
    $value = a_whole_lotta_processing();

    // Cache the value.
    wp_cache_set( $cache_key, $value );

    return $value;
}

// Use this as a global variable or something.
$cache = new \DuckDev\Cache\Cache();

function do_something() {
    return $cache->remember( 'some-cache-key', function () {
        return a_whole_lotta_processing();
    } );
}

function get_latest_posts() {
    return $cache->remember( 'latest_posts', function () {
        return new WP_Query( array(
            'posts_per_page' => 5,
            'orderby'        => 'post_date',
            'order'          => 'desc',
        ) );
    }, 'my-cache-group', HOUR_IN_SECONDS );
}

function show_error_message() {
    $error_message = $cache->forget( 'form_errors', 'my-cache-group', false );

    if ( $error_message ) {
        echo 'An error occurred: ' . $error_message;
    }
}

function get_tweets() {
    $user_id = get_current_user_id();
    $key     = 'latest_tweets_' . $user_id;

    return $cache->persist( $key, function () use ( $user_id ) {
        return get_latest_tweets_for_user( $user_id );
    }, 15 * MINUTE_IN_SECONDS );
}