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;
}
2 Answers
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.