想在wordpress中显示提示类别中的随机提示,并且每24小时更改一次......是否可能?
这是我的查询
// 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();
}
答案 0 :(得分:3)
您可以使用 WP Transients API 并使用类似的内容:
<?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 );
} ?>
希望它对你有所帮助。
答案 1 :(得分:1)
您可以使用Transients API类,它可以以秒为单位存储您的数据。
所以,这是修改后的代码:
<?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();
}
}
?>
答案 2 :(得分:0)
添加到Jenis,如果发布新帖子,删除缓存可能会很有趣,你可以用一个小钩子来做。
(至少就是我在使用Transients API缓存结果时所做的事情。)
// 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')