WordPress 对自定义的sql查询结果进行缓存

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

使用场景:首页调用最新评论、自定义获取最*的文章的sql语句
function d4p_get_query_results() {
global $wpdb;

$data = get_transient('my_transient_key');

if ($data === false) {
$data = $wpdb->get_results(' // SQL 语句 // ');
set_transient('my_transient_key', $data, 3600 * 24);
}

return $data;
}

删除缓存方法
delete_transient('my_transient_key');

latest 10 posts sql

global $wpdb;
$transient_name = 'lc-latest-10-posts';
$post_ids = get_transient( $transient_name );
if ( $post_ids == FALSE ){
$sql = "SELECT post.ID
FROM $wpdb->posts post
WHERE
post.post_type = 'post'
AND post.post_status = 'publish'
ORDER BY post.post_date
DESC
LIMIT 0,10";
$results = $wpdb->get_col( $sql );
if( $results ){
foreach ( $results as $result ){
$post_ids[] = $result;
}
set_transient( $transient_name, $post_ids, 60 * 60 * 6 );
}
}

Leave a Comment