Reputation: 11
Would like to show a random tip from tips category in wordpress and change it every 24hrs... is it possible?
Here is my query
// Random post link
function randomPostlink(){
$RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand'));
while ( $RandPostQuery->have_posts() ) : $RandPostQuery->the_post();
echo the_permalink();
endwhile;
wp_reset_postdata();
}
Upvotes: 1
Views: 658
Reputation: 880
Adding to Jenis it might be interesting to delete the cache if a new post is published, you can do it with a little hook.
(At least that´s what I am doing when using the Transients API to cache results.)
// Delete caches, when a new post is published
function delete_cache_after_publishing_new() {
delete_transient('your_cache_1');
delete_transient('your_cache_2');
}
add_action('publish_post','delete_cache_after_publishing_new')
Upvotes: 0
Reputation: 431
You can use the class Transients API which can store your data with a expire time in seconds.
So, here is the modified code :
<?php
// Your function
function randomPostlink(){
// Get the cache data
$rand_tip = get_transient( 'rand_tip' );
// Launch the request if the data do not exist or the data has expired
if ( $rand_tip === false ) {
// Args for the WP_Query
$args = array(
'post_type' => array( 'tip' ),
'posts_per_page' => 1,
'orderby'=>'rand'
);
// Generate the datas
$rand_tip = new WP_Query($args);
// Set the ID of the request
set_transient( 'rand_tip', $rand_tip, 24 * HOUR_IN_SECONDS );
}
// Loop the posts
if ( $rand_tip->have_posts() ) {
while ( $rand_tip->have_posts() ) : $rand_tip->the_post();
// Echo the permalink
the_permalink();
endwhile;
// Reset the post data
wp_reset_postdata();
}
}
?>
Upvotes: 1
Reputation: 1613
You can make use of WP Transients API and use it something like that :
<?php
// Check for transient. If none, then execute WP_Query
if ( false === get_transient( 'special_query_results' ) ) {
$RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand'));
// Put the results in a transient. Expire after 24 hours.
set_transient( 'special_query_results', $RandPostQuery , 24 * HOUR_IN_SECONDS );
} ?>
Hope it helps you.
Upvotes: 3