wordpress分页_WordPress瞬态指南

wordpress分页

WordPress provides us with a wonderful API for managing options. Options are ridiculously simple: they each have a name and a value and are stored in the WordPress database - in the options table - for safe keeping. Options can store anything from your Google Maps API key to an array of data or even the HTML code for your sidebar.

WordPress为我们提供了一个用于管理选项的出色API。 选项非常简单:每个选项都有一个名称和一个值,并存储在WordPress数据库中(在选项表中)以安全保存。 选项可以存储从Google Maps API密钥到数据数组甚至侧栏HTML代码的所有内容。

Transients are similar in all but one property; they have an expiration time. This makes them uniquely suited to act as a cache for appropriate data. In addition to reducing the number of queries our website utilizes, they can be further sped up by caching plugins which may make WordPress store transients in fast memory (like Memcached) instead of the database.

除了一个属性外,瞬态在所有属性上都是相似的。 他们有到期时间。 这使得它们特别适合用作适当数据的缓存。 除了减少我们网站使用的查询数量之外,还可以通过缓存插件进一步加快查询速度,这些插件可以使WordPress将瞬态存储在快速内存(例如Memcached)而不是数据库中。

In this post I'll take you through the code you need to know to use transients and show you some advanced examples of how they can be utilized. I'd like to focus on the fact that transients can be used as an easy cache mechanism for any object, not just simple strings or WordPress related objects.

在本文中,我将带您了解使用瞬态所需的代码,并向您展示如何使用瞬态的一些高级示例。 我想关注一个事实,即瞬变可以用作任何对象的简便缓存机制,而不仅仅是简单的字符串或与WordPress相关的对象。

基本操作 (Basic Operations)

The three basic operations available are: get, set and delete. Each operation has a site-specific version and a network-wide version which is used if a transient should be made available to the whole multisite network. Based on this extremely simple interface we can build pretty sophisticated systems to speed up our website considerably.

可用的三个基本操作是: getsetdelete 。 每个操作都有特定于站点的版本和整个网络的版本,如果应该使整个多站点网络都可以使用瞬态,则可以使用该版本。 基于这个非常简单的界面,我们可以构建非常复杂的系统,以大大加快我们的网站的速度。

设定瞬态 (Setting Transients)

By using the set_transient() function we can create a transient. The function takes two required and one optional parameter. The first one is the name of the transient, the second is the value, the third is the expiration time.

通过使用set_transient()函数,我们可以创建一个瞬态。 该函数带有两个必需参数和一个可选参数。 第一个是瞬变的名称,第二个是值,第三个是到期时间。

set_transient( 'my_mood', 'Pretty Awesome', 28800 ); // Site Transient
set_site_transient( 'my_mood', 'Pretty Awesome', 28800 ); // Multisite Transient

When the code above is executed it stored my current mood for 28800 seconds (8 hours). Note that you can not retrieve the value of the transient after the expiration date, it will no longer exist.

当上面的代码执行时,它存储了我当前的心情28800秒(8小时)。 请注意,您不能在到期日期之后检索瞬态的值,它将不再存在。

瞬变 (Getting Transients)

Retrieving the value of transients is even simpler than setting them. By utilizing the get_transient() functions and passing the transient name as the first - and only - parameter we can retrieve the value of our transient.

检索瞬态值比设置瞬态值更简单。 通过使用get_transient()函数并将瞬态名称作为第一个(也是唯一的)参数传递,我们可以检索瞬态的值。

$my_mood = get_transient( 'my_mood' ); // Site Transient
$my_mood = get_site_transient( 'my_mood' ); // Multisite Transient

Be mindful of the return value when creating your transients! If the transient has expired, doesn't exist or doesn't have a value the function returns 'false'. This means that you should use the identity operator (===) instead of the equality operator (==) when checking the value. It also means that you should not store plain boolean values, convert them to integers instead.

创建瞬变时要注意返回值! 如果瞬变已过期,不存在或没有值,则该函数返回“ false”。 这意味着在检查值时,应使用身份运算符( === )而不是相等运算符( == )。 这也意味着您不应该存储纯布尔值,而是将其转换为整数。

删除瞬态 (Deleting Transients)

In many cases you'll want to delete transients before they expire which is when the delete_transient() function comes in handy. It takes one parameter, the name of the transient.

在许多情况下,您需要在瞬变过期之前删除它,这是在delete_transient()函数派上用场的时候。 它采用一个参数,即瞬变的名称。

delete_transient( 'my_mood' ); // Site Transient
delete_site_transient( 'my_mood' ); // Multisite Transient

到期深度 (Expiration In-Depth)

The most important thing to keep in mind is that transients which never expire - have an expiration set to 0 - are autoloaded, other transients are not autoloaded. We can use this to our advantage by figuring out which transients are used frequently.

要记住的最重要的一点是,永不过期的瞬态(将过期设置为0)会自动加载,其他瞬态则不会自动加载。 我们可以通过找出经常使用的瞬态来利用这一点。

永不过期的瞬态 (Never Expiring Transients)

So what is the point of a transient which never expires? You could use it to store a custom recent posts widget for example. This transient can be deleted and re-set when a new post is published so we don't need to give it an expiration. Since the expiration is set to 0 the transient is autoloaded which is perfect if we want to show it on all pages.

那么,永不消失的瞬态有什么意义呢? 例如,您可以使用它来存储自定义的最近帖子小部件。 可以在发布新帖子时删除并重新设置此瞬态,因此我们不需要为其赋予过期时间。 由于到期时间设置为0,因此会自动加载瞬态,如果要在所有页面上显示瞬态,这是完美的选择。

If you only show the widget on your about page there really is no need to autoload the transient. In this case it is better to give it an extremely large expiration date like 3153600000 which would be 100 years.

如果仅在“关于”页面上显示小部件,则实际上不需要自动加载瞬态。 在这种情况下,最好给它一个非常大的到期日期,例如3153600000 ,这将是100年。

时间常数 (Time Constants)

Since WordPress 3.5 time constants have been available to give developers easy access to time in seconds.

自从WordPress 3.5开始,时间常数就可以使开发人员轻松地访问时间(以秒为单位)。

set_transient( 'my_mood_today', 'Pretty Awesome', DAY_IN_SECONDS );

The following five constants can be used:

可以使用以下五个常量:

set_transient( 'my_mood_today', 'Pretty Awesome', MINUTE_IN_SECONDS );
set_transient( 'my_mood_today', 'Pretty Awesome', HOUR_IN_SECONDS );
set_transient( 'my_mood_today', 'Pretty Awesome', DAY_IN_SECONDS );
set_transient( 'my_mood_today', 'Pretty Awesome', WEEK_IN_SECONDS );
set_transient( 'my_mood_today', 'Pretty Awesome', YEAR_IN_SECONDS );

瞬态的用途 (The Uses Of Transients)

When talking about transients the biggest error people make is that they seem to think it is for discreet data only. My mood, time of day, current temperature. All good, all time-sensitive so all ripe for transiency.

当谈论瞬态时,人们犯的最大错误是他们似乎认为这仅适用于谨慎的数据。 我的心情,一天中的时间,当前的温度。 一切都很好,所有的时间敏感,所以一切都变得短暂。

Looking beyond simple data you can figure out tons of great ways to use transients. Think about data that changes on your site, but not too frequently. A widget or a whole sidebar could be a good example. Is it really necessary to perform database queries each time your sidebar is shown?

除了简单的数据,您还可以找到大量使用瞬态的好方法。 考虑一下您网站上的数据更改,但不要太频繁。 小部件或整个侧栏可能是一个很好的示例。 确实需要在每次显示侧边栏时执行数据库查询吗?

Creating the navigation menu is also a pretty database-intensive task. Once the website admin has assembled the required menu structure it rarely changes. Why not load the whole thing from a transient? Using hooks we can still force a re-load if menu items change.

创建导航菜单也是一项非常耗费数据库的任务。 网站管理员组装好所需的菜单结构后,便很少更改。 为什么不从瞬态加载整个内容呢? 如果菜单项发生更改,我们仍然可以使用钩子强制重新加载。

How about a section at the bottom of each single post which shows a couple of interesting posts from your archives. Why pull this from the database on every single page load when you could cache it as a transient and re-load it no more than once every hour?

每个帖子底部的一个部分怎么样,它显示了您存档中几个有趣的帖子。 为什么可以在每次页面加载时将其从数据库中提取出来,而您却可以将其作为瞬态缓存并每小时重新加载一次不超过一次?

缓存导航菜单 (Caching The Navigation Menu)

A theme usually uses wp_nav_menu() to output a menu. Parameters are passed to this function and the correct menu is displayed. This function returns the menu in HTML form which is great, it's a string we can easily store as a transient. Let's create a function which will replace wp_nav_menu() in our theme.

主题通常使用wp_nav_menu()输出菜单。 将参数传递给此功能,并显示正确的菜单。 该函数以HTML格式返回菜单,这是很棒的,这是一个我们可以轻松存储为瞬态的字符串。 让我们创建一个将替换主题中的wp_nav_menu()的函数。

function scotch_transient_menu( $args = array() ) {
    $defaults = array(
        'menu' => '',
        'theme_location' => '',
        'echo' => true,
    );

    $args = wp_parse_args( $args, $defaults );

    $transient_name = 'scotch_menu-' . $args['menu'] . '-' . $args['theme_location'];
    $menu = get_transient( $transient_name );

    if ( false === $menu ) {
        $menu_args = $args;
        $menu_args['echo'] = false;
        $menu = wp_nav_menu( $menu_args );
        set_transient( $transient_name, $menu, 0 );
    }

    if( false === $args['echo'] ) {
        return $menu;
    }

    echo $menu;

}

Our scotch_transient_menu() function takes the same arguments as wp_nav_menu(). I've made sure that the menu, theme_location and echo parameters have default values. Since we use outside of passing them to wp_nav_menu() they must have a value, otherwise a PHP notice will be thrown.

我们的scotch_transient_menu()函数采用与wp_nav_menu()相同的参数。 我已经确保menutheme_locationecho参数具有默认值。 由于我们在将它们传递给wp_nav_menu()之外使用它们,所以它们必须具有值,否则将抛出PHP通知。

For each menu we create a transient with the naming scheme of scotch_menu-[menu]-[location]. This allows for flexible use within themes that may call for multiple menus. If you have a single menu you don't need to get fancy like this, you can just hard-code this with it's menu ID.

对于每个菜单,我们使用scotch_menu- [menu]-[location]的命名方案创建一个过渡。 这允许在可能需要多个菜单的主题中灵活使用。 如果您只有一个菜单,则不需要花哨的时间,只需使用菜单ID对其进行硬编码即可。

We try and retrieve the menu using the get_transient() function. Remember that this should return false if the transient has expired, has no value or doesn't exist. We use this to determine if we need to refresh our cache.

我们尝试使用get_transient()函数检索菜单。 请记住,如果瞬变已过期,没有值或不存在,则此方法应返回false 。 我们使用它来确定是否需要刷新缓存。

If the $menu variable is false, I create a new array of options to pass to the wp_nav_menus() function. The reason for this is that we need to make sure the echo parameter is false while retrieving the menu. We may echo it later, but we need the return data first to store as the transient.

如果$menu变量为false,我将创建一个新的选项数组,以传递给wp_nav_menus()函数。 原因是我们在检索菜单时需要确保echo参数为false。 我们可能稍后会回显它,但我们需要首先将返回数据存储为瞬态。

The next step is to set the transient. Since the menu is likely to be shown on every page I thought giving it an expiration of 0 would be best, since it would be autoloaded.

下一步是设置瞬变。 由于菜单可能会显示在每个页面上,所以我认为给它一个0的到期时间是最好的,因为它将被自动加载。

So far so good, our menu is now cached and served with the minimum amount of fuss. The problem we're facing now is that changes in our menus will never be reflected on our site. This is where hooks come in which allow us to update our cached value.

到目前为止,到目前为止,我们的菜单已被缓存并以最小的麻烦量提供。 我们现在面临的问题是菜单中的更改永远不会反映在我们的网站上。 这是允许我们更新缓存值的挂钩。

The wp_update_nav_menu action is fired whenever a menu item is updated. If we create a function that updates our cached value each time we are in the clear.

每当更新菜单项时,都会触发wp_update_nav_menu操作。 如果我们创建一个函数,该函数每次清除都会更新我们的缓存值。

add_action( 'wp_update_nav_menu', 'scotch_update_menus' );
function scotch_update_menus() {
    global $wpdb;
    $menus = $wpdb->get_col( 'SELECT option_name FROM $wpdb->options WHERE option_name LIKE "scotch_menu-%" ' );
    foreach( $menus as $menu ) {
        delete_transient( $menu );
    }
}

This is a bit crude but it does the job. Since we need to find all menus possible we need to manually look through the database to match our naming convention. This would also be a lot easier if you just need to cater to a specific menu.

这有点粗糙,但可以完成工作。 由于我们需要找到所有可能的菜单,因此我们需要手动浏览数据库以匹配我们的命名约定。 如果您只需要满足特定的菜单,这也将容易得多。

In conclusion our menus our now highly optimized. They are served from an autoloaded transient so no database queries are necessary apart from loading the option. Whenever a menu item chnges our transient is deleted and the menu will be rebuilt whenever someone accesses the site.

总之,我们的菜单现已高度优化。 它们是从自动加载的瞬变中提供的,因此除了加载选项之外,无需数据库查询。 每当菜单项更改时,我们的过渡都会被删除,并且只要有人访问该站点,该菜单就会被重建。

创建最近的项目部分 (Creating A Recent Projects Section)

Suppose you have a personal site an on your about page you list your recent projects. The list comes from a custom post type, the code looks something like this:

假设您有一个个人站点,并且在“关于”页面上列出了最近的项目。 该列表来自自定义帖子类型,代码如下所示:

$args = array(
    'post_type'   => 'project',
    'post_status' => 'publish'
);
$projects = new WP_Query( $args );

if ( $projects->have_posts() ) {
    echo '<ul>';
    while( $projects->have_posts() ) {
        echo '<li><a href="' . get_permalink() . '">' . the_title( '', '', false ) . '</a></li>';
    }
    echo '</ul>';
}

Each time the page is loaded the database query is made, even if you take on a new project every 5 yeaars. What a waste! Let's fix this shall we? We'll use the same thinking is we did in our previous example, with two small changes.

每次加载页面时,都会进行数据库查询,即使您每5年进行一次新项目也是如此。 真浪费! 让我们解决这个问题吧? 我们将使用与上一个示例相同的想法,但有两个小的更改。

$projects = get_transient( 'scotch_cached_projects' );
if ( false === $projects ) {
    $args = array(
        'post_type'   => 'project',
        'post_status' => 'publish'
    );

    $projects = new WP_Query( $args );

    set_transient( 'scotch_cached_projects', $projects, DAY_IN_SECONDS );
}

if( $projects->have_posts() ) {
    echo '<ul>';
    while( $projects->have_posts() ) {
        echo '<li><a href="' . get_permalink() . '">' . the_title( '', '', false ) . '</a></li>';
    }
    echo '</ul>';
}

In this instance we used an actual expiration time. This would be appropriate if you really don't care if your new project shows up a day after you add it to your site.

在这种情况下,我们使用了实际的到期时间。 如果您真的不在乎新项目是否在添加到网站后的第二天出现,这将是适当的。

If making sure that the project shows up immediately is important then I suggest adding a large expiration time. While we could set it to 0, this would make this transient autoload and we don't really need it on every page. So in this case we'll give it a far future expiration and create a function to flush our transient when a new project is published.

如果确保立即显示项目很重要,那么我建议增加一个较大的到期时间。 虽然我们可以将其设置为0 ,但这将使此瞬态自动加载,并且我们并不是每个页面上都需要它。 因此,在这种情况下,我们将给它一个远期的到期时间,并在发布新项目时创建一个函数来刷新瞬态。

add_action( 'publish_post', 'scotch_purge_project_transient' );
function scotch_purge_project_transient( $ID, $post ) {
    if ( 'project' == $post->post_type ) {
        delete_transient( 'scotch_cached_projects' );
    }
}

结论 (Conclusion)

I hope it is clear from this article that transients are much more than a cute little companion to the options API. When used correctly they provide a huge speed benefit to your website or at least decrease the resources used by your server.

我希望从本文中可以清楚地了解到,瞬态不仅是options API的可爱小伴侣。 如果使用正确,它们可以为您的网站带来巨大的速度优势,或者至少减少服务器使用的资源。

Transients can store anything from an array of your most active commentors to whole post objects if needed.

如果需要,瞬态可以存储从最活跃的评论者数组到整个post对象的任何内容。

Always keep in mind that caching can lead to a decrease in usability. Just because something can be stored as a transient doesn't mean it should be stored there.

请始终记住,缓存会导致可用性降低。 仅仅因为某些东西可以被存储为瞬态并不意味着它应该被存储在那里。

If you use the transients API for something particularly awesome let us know in the comments!

如果您将暂态API用于特别出色的功能,请在评论中告诉我们!

翻译自: https://scotch.io/tutorials/a-guide-to-transients-in-wordpress

wordpress分页

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值