Created
May 1, 2023 07:54
-
-
Save waqashassan98/5e55460c108bba7629219c30a4c3d04e to your computer and use it in GitHub Desktop.
Initialising and using Transients in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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