通过使用Transients API缓存自定义查询来加快WordPress的速度

O boy, the title sounds scary doesn’t it. You have nothing to worry because we will break it all down. Is your theme running custom WordPress queries to show random posts, popular posts, recent posts etc in the sidebar or anywhere else? If yes, then you should consider using the WordPress transient API to cache these queries to reduce resource consumption as well as helping the load time. In this article, we will show you how to speed up your WordPress site by caching custom queries using the Transients API.

哦,男孩,标题听起来很吓人,不是吗。 您不用担心,因为我们会分解所有内容。 您的主题是否正在运行自定义WordPress查询,以在侧边栏或其他任何地方显示随机帖子热门帖子近期帖子等? 如果是,那么您应该考虑使用WordPress瞬态API来缓存这些查询,以减少资源消耗并缩短加载时间。 在本文中,我们将向您展示如何通过使用Transients API缓存自定义查询来加快WordPress网站的速度。

Note: You need to understand how WordPress themes work (loops etc), in order for you to follow this post.

注意:您需要了解WordPress主题的工作原理(循环等),以便您阅读本文。

So this whole caching and transient lingo is going over my head. Well don’t worry let us explain what it does. Basically if you are running a site like List25 and have a loop that shows 6 random posts in your sidebar, then transient API can help. Every time a user refreshes the page, that custom WP Query that you have will go in your database and pull 6 posts at random. If you are a relatively new site, it shouldn’t be that bad. But if you are getting A LOT of people to your site, then it can crash your SQL server, and you will see the “Error Establishing Database Connection” screen. By adding a few extra lines of code, you can easily store the results of that query (cache it) for a certain period of time using the Transients API.

因此,整个缓存和短暂的术语让我感到头疼。 好吧,别担心,让我们解释一下它的作用。 基本上,如果您正在运行类似List25的网站,并且有一个循环在侧边栏中显示6个随机帖子,那么临时API可以提供帮助。 每次用户刷新页面时,您拥有的自定义WP查询将进入数据库并随机提取6个帖子。 如果您是一个相对较新的网站,那应该没那么糟。 但是,如果您有很多人访问您的站点,则它可能会使您SQL Server崩溃,并且您将看到“建立数据库连接错误”屏幕。 通过添加一些额外的代码行,您可以使用Transients API轻松地将查询结果存储(缓存)一定时间。

Example of the loop code that we had for pulling random posts:

我们用于提取随机帖子的循环代码示例:


<?php $random_query = new WP_Query('orderby=rand&posts_per_page=6');
while ($random_query->have_posts()) : $random_query->the_post();
?>
<div class="gridcontainer">
<div class="gridthumb"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="gridcontent">
<div class="gridtext"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></div>
</div>
</div>
<?php endwhile; ?>

The coolest part about our random posts query in the sidebar was it showed new content every time. So by caching the query for 12 hours, we will have the same 6 posts showing for 12 hours right? Well, we found a work around thanks to the suggestion of our friend Konstantin Kovshenin (@kovshenin). He suggested that instead of using WP_Query, we use get_posts and pull 20 posts instead. Cache the results of that query using the transients API, and then use the array_rand() function to show only 6 posts out of the original 20 at random. This way we can keep simulate the random effect on the site.

边栏中有关随机帖子查询的最酷的部分是每次都显示新内容。 因此,通过将查询缓存12小时,我们将有12个小时显示相同的6个帖子,对吗? 好吧,我们在朋友Konstantin Kovshenin(@kovshenin)的建议下找到了工作。 他建议不要使用WP_Query,而要使用get_posts并提取20个帖子。 使用暂态API缓存该查询的结果,然后使用array_rand()函数随机显示原始20条帖子中的6条。 这样,我们可以保持模拟站点上的随机效果。

First thing we did was set the transient. We got the code from the WordPress Codex page.

我们要做的第一件事是设置瞬态。 我们从WordPress Codex页面获得了代码。


// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
	$randargs = array('orderby' => 'rand', 'numberposts' => 20);
	$special_query_results = get_posts($randargs);
    set_transient( 'special_query_results', $special_query_results, 60*60*12 );
}

Notice the 60*60*12 is the area where you can control the length of the cache. Feel free to change it to whatever you like. Now if we show the $special_query_results using the foreach loop, we will have all 20 posts displayed. So we need to utilize the array_rand() function to only pull 6 items at random. We added the code like this:

注意60 * 60 * 12是您可以控制缓存长度的区域。 随时将其更改为您喜欢的任何内容。 现在,如果我们使用foreach循环显示$ special_query_results,我们将显示所有20条帖子。 因此,我们需要利用array_rand()函数仅随机提取6个项目。 我们添加了如下代码:


$randomposts = get_transient( 'special_query_results' );
$randkey = array_rand( $randomposts, 6 );

Now this will pull out 6 post IDs at random from our transient data. However, it will not pull the values for each post. So we had to do add this bits of code:

现在,这将从我们的瞬态数据中随机抽取6个帖子ID。 但是,它不会提取每个帖子的值。 因此,我们必须添加以下代码:


$sixposts[0] = $randomposts[$randkey[0]];
$sixposts[1] = $randomposts[$randkey[1]];
$sixposts[2] = $randomposts[$randkey[2]];
$sixposts[3] = $randomposts[$randkey[3]];
$sixposts[4] = $randomposts[$randkey[4]];
$sixposts[5] = $randomposts[$randkey[5]];

Basically we created an array for $sixposts in which we assign a value to each of those items. Not sure if this was the best way of going about it, but it worked. If any of you have better suggestions, then feel free to post it in the comments.

基本上,我们为$ sixposts创建了一个数组,在其中为每个项目分配一个值。 不确定这是否是解决问题的最佳方法,但它确实有效。 如果您有更好的建议,请随时在评论中发布。

After doing that, we are now ready to display the loop. Simply put the code like this:

这样做之后,我们现在准备显示循环。 只需将代码如下所示:


global $post; //required for it to work
foreach( $sixposts as $post ) :  setup_postdata($post);

//All the items go here.

endforeach; 

setup_postdata allows you to use all loop tags inside this foreach loop such as the_permalink etc.

setup_postdata允许您使用此foreach循环内的所有循环标签,例如the_permalink等。

To make it easy for everyone, here is the final code that we have:

为了让所有人都容易,这是我们拥有的最终代码:


<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
	$randargs = array('orderby' => 'rand', 'numberposts' => 20);
	$special_query_results = get_posts($randargs);
    set_transient( 'special_query_results', $special_query_results, 60*60*12 );
}

// Use the data like you would have normally...
$randomposts = get_transient( 'special_query_results' );
$randkey = array_rand( $randomposts, 6 );
$sixposts[0] = $randomposts[$randkey[0]];
$sixposts[1] = $randomposts[$randkey[1]];
$sixposts[2] = $randomposts[$randkey[2]];
$sixposts[3] = $randomposts[$randkey[3]];
$sixposts[4] = $randomposts[$randkey[4]];
$sixposts[5] = $randomposts[$randkey[5]];

global $post;
foreach( $sixposts as $post ) :  setup_postdata($post); ?>

<div class="gridcontainer">
<div class="gridthumb"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="gridcontent">
<div class="gridtext"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></div>
</div>
</div>

<?php endforeach; ?>

Ta da, now you are only making this DB query once every 12 hours no matter how many users are visiting your site.

达达,现在无论有多少用户访问您的网站,您只需要每12小时进行一次数据库查询。

翻译自: https://www.wpbeginner.com/wp-tutorials/speed-up-your-wordpress-by-caching-custom-queries-using-transients-api/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值