您可以使用WP_Object_Cache 与持久缓存插件结合使用,或者您可以使用Transient API.
WP_Object_Cache:
// Random post link
function randomPostlink(){
$cache = wp_cache_get( \'random_tip_link\' );
if( $cache ) {
echo $cache;
} else {
ob_start();
$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();
}
wp_reset_postdata();
$cache = ob_get_flush();
wp_cache_set( \'random_tip_link\', $cache );
}
}
Transient API:
// Random post link
function randomPostlink(){
$cache = get_transient( \'random_tip_link\' );
if( $cache ) {
echo $cache;
} else {
ob_start();
$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();
}
wp_reset_postdata();
$cache = ob_get_flush();
set_transient( \'random_tip_link\', $cache, DAY_IN_SECONDS );
}
}
如果需要使用或不使用持久缓存插件缓存查询,请使用瞬态API,该API将数据库用于缓存结果,如果启用了持久缓存,则将使用WP\\U Object\\U缓存: