Save SQL query time and improve WordPress performance by caching query results with the WordPress Transients API.

WordPress性能的瓶颈很多时候都在 MySQL数据库查询上,如果能把查询数据缓存起来,对提高 WordPress 性能很有帮助,WordPress 为我们提供了 Transients API 供我们缓存数据。

根据服务器设置,Transients API 会把缓存数据存储到不同的位置,如果服务器上有 Memcached 之类的对象缓存插件,缓存数据就直接存储在内存中,如果没有缓存插件,缓存数据存储在了 WordPress 的数据表中。

//检查缓存是否已经存在
if( false === ( $portfolio_query = get_transient( 'saved_product_query' ) ) ) {

//如果没有缓存,进行WordPress查
    $portfolio_query = new WP_Query( array(
        'post_type' => 'product',
	'posts_per_page' => 10,
    ) );

    set_transient( 'saved_product_query', $portfolio_query , 60*60*4 ); //设置缓存,时间为4个小时
}

//if( have_posts() ) {  } ...在这里输入查询结果

//更新时,删除缓存
function wpc_delete_its_transients() {
    global $post;
    if( $post->post_type == 'portfolio' ) {
	 delete_transient( 'saved_product_query' );
    }
}
add_action( 'save_post', 'wpc_delete_its_transients' );

以上代码中,WordPress 会先查询是否有缓存数据,如果有缓存数据,直接返回缓存的数据,如果没有,进行MySQL查询,设置缓存供下次使用,然后返回查询到的数据。

WordPress模板或插件中复杂查询比较多的时候,Transients API 的效果是很明显的。当然,如果你使用的有类似 wp super cache 之类的插件,以上的代码就是多余的了,因为 wp super cache,直接生成了静态数据,缓存效果比以上代码是要好的。

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *