试试这个-它应该适合你的需要。注意,我几乎没试过。。。在现场环境中使用之前,请先进行自我测试。
// calculate times
$second = 1;
$minute = $second * 60;
$hour = $minute * 60;
$day = $hour * 24;
$days = $day * 3;
$time = time(); //get current timestamp
$random_post_timestamp = get_option(\'my_random_post_timestamp\'); //get timestamp of queried post
if( $random_post_timestamp ) {
$diff = $time - $random_post_timestamp;
if( $diff >= $days ) { // if timestamp older than 3 days, delete the option
delete_option(\'my_random_post\');
delete_option(\'my_random_post_timestamp\');
}
}
if( get_option(\'my_random_post\') ) { // is there a option with my id?
//yes, it shoukd be used in my query
$args = array( \'p\' => get_option(\'my_random_post\') );
} else {
//no, query a new one
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' => 1,
\'limit\' => 1,
\'orderby\' => \'rand\',
\'meta_key\' => \'already_shown_in_random\',
\'meta_compare\' => \'NOT EXISTS\' //only query posts that don\'t have a the \'already_shown_in_random\' meta
);
}
// the query
$random_post = new WP_Query($args);
if( $random_post->have_posts() ):
while( $random_post->have_posts() ): $random_post->the_post();
if( !get_option(\'my_random_post\') ) { //if not already populated, store my id and the current timestamp in the options
add_option(\'my_random_post\', get_the_id() );
add_option(\'my_random_post_timestamp\', time() );
add_post_meta( get_the_id() , \'already_shown_in_random\', \'yes\'); //add a post meta so that this post isnt queried a second time
}
/* DO YOUR STUFF HERE!!!!! */
endwhile;
wp_reset_postdata();
endif;
它做什么
Rarst 在他之前的回答中。。。