3

I have a small shortcode which basically takes data from a JSON file and displays it on a page. The data in JSON is updated weekly, how can I use a transient so the data for the current week is cached?

Here is my shortcode

function week_agenda() {
        $days = json_decode(file_get_contents('json_file'));
        unset($days[0]);
        ob_start();
    ?>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th> Title </th>
                    <th>Content</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($days as $data) { ?>
                <tr>
                    <td><?php echo $data[0]; ?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
    <?php
    $output = ob_get_clean();
    return $output;
}
4

Use this instead of the line in wich you define $days (your second line):

$transient = get_transient( 'your_transient_key' );

if( !$transient ):

    $days = file_get_contents( 'json_file' );

    set_transient( 'your_transient_key', $days, DAY_IN_SECONDS*7 );


else:

    $days = $transient;

endif;

$days = json_decode( $days );

... 

May be a bit rough but you get the idea.

  • Perfect, works fine :) – Radu033 Nov 13 '17 at 11:06
  • Glad i could help ;) I think there is no further explanation of the code necessary or is it? – GDY Nov 14 '17 at 6:41
4

I add it the transient name to a variable to handle it easier.

Next, I check if the return value from the get_transient is false and update the variable name and the transient. You can try this one:

    $transient_name = 'cached_json_data';
    if ( false === ( $json_data = get_transient( $transient_name ) ) ) {
      $json_data = json_decode(file_get_contents('json_file'));
      set_transient( $transient_name, $json_data, WEEK_IN_SECONDS );
    }

//normal code

set_transient

You do not need to serialize values. If the value needs to be serialized, then it will be serialized before it is set.

Constants WP 3.5+

MINUTE_IN_SECONDS  = 60 (seconds)
HOUR_IN_SECONDS    = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS     = 24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS    = 7 * DAY_IN_SECONDS
MONTH_IN_SECONDS   = 30 * DAY_IN_SECONDS
YEAR_IN_SECONDS    = 365 * DAY_IN_SECONDS
  • +1 for the compact sytax and the detailed answer. Could also be the accepted answer. – GDY Nov 14 '17 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.