Skip to content

Instantly share code, notes, and snippets.

@waqashassan98
Created May 1, 2023 07:54
Show Gist options
  • Save waqashassan98/5e55460c108bba7629219c30a4c3d04e to your computer and use it in GitHub Desktop.
Save waqashassan98/5e55460c108bba7629219c30a4c3d04e to your computer and use it in GitHub Desktop.
Initialising and using Transients in WordPress
<?php
// Check for transient. If none, then execute WP_Query
if ( false === ( $featured = get_transient( 'foo_featured_posts' ) ) ) {
$featured = new WP_Query(
array(
'category' => 'featured',
'posts_per_page' => 5
)
);
// Put the results in a transient. Expire after 12 hours.
set_transient( 'foo_featured_posts', $featured, 12 * HOUR_IN_SECONDS );
}
?>
// Run the loop as normal
<?php if ( $featured->have_posts() ) : ?>
<?php while ( $featured->have_posts() ) : $featured->the_post(); ?>
// featured posts found, do stuff
<?php endwhile; ?>
<?php else: ?>
// no featured posts found
<?php endif; ?>
<?php wp_reset_postdata(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment