search
HomeCMS TutorialWordPressWordPress Web Application Development Guide: Detailed explanation of available features (Part 7): Caching Technology

WordPress Web应用开发指南:可用功能详解(第7部分):缓存技术

One of the most important things we must always pay attention to when building web applications is performance.

As they say, performance is a feature.

Whether you're a designer, developer, or user, you know this intuitively: when it comes to apps, we hate waiting. We get frustrated when things don't work fast enough, or we have to wait longer than we think we should.

To this end, most modern web development frameworks can implement some type of caching by using some API, and WordPress (albeit a base) is no exception.

So, as we continue our discussion of why WordPress is a viable choice as a foundation for web application development, we will look at the APIs provided by the core application, how they work and how we can use them to our advantage, and how Improve performance further with additional caching plugins.


Why is caching important?

In short, caching is important because it allows us to store frequently retrieved data somewhere in memory so that it can be retrieved quickly.

When you look at the bigger picture, this becomes increasingly apparent when multiple users view a website. What I mean is, if one person (or very few people) visits a website, and that website stores its data in a database, then every time the page is loaded, that information has to be retrieved from the website. database, inserted into the page, and returned to the user.

If a certain level of cache is established, there is no need to call the database frequently. Instead, information can be pulled from an area in memory, allowing for faster retrieval and therefore faster page load times.

We will introduce the technical details of this in detail later in this article.

What about plugins?

If you’ve been using WordPress for a long time, you’re probably familiar with the many caching plugins available.

These are undoubtedly great solutions for speeding up your website and/or web application, but it does raise the question: if you can use a plugin to do this, then why should we worry about it?

Of course, this is a valid question, but plugins can only do so much on their own.

Developers can build their applications in such a way that they not only perform well without caching mechanisms, but are also greatly enhanced by said caching plugins.

What I mean is that these caching plugins look for data that themes and applications want to store somewhere, and if we can do this programatically in our own working context, then these plugins will yield a much larger Effect performance.

After understanding the available APIs, we will revisit this topic later in this article and see how they can improve the performance of cache plugins.


Transient API

In order to introduce first-level caching into our application, we need to leverage WordPress’s Transients API. First, please note that the official definition of a transient is “something that exists only for a short period of time.”

As defined in the Codex Alimentarius:

[Transient API] provides a simple and standardized way to temporarily store cached data by giving it a custom name and a time range after which the data will expire and be deleted. in the database.

But what does it mean? After all, the data is still stored in the database, so why is this better than storing the data in any other database table (such as the wp_options table?)?

We'll discuss this in more detail once we revisit the discussion about caching and plugins.

Set transient

Setting transient values ​​is actually as simple as storing the data in an options table.

Specifically, you need a key value that uniquely identifies the data, and then a value associated with that key. You also need an expiration time (in seconds) to keep the data in the table before refreshing the table.

Suppose we want to store the current user's name as the last or most recently active user on the site. We can do this using the wp_get_current_user() function.

First, we will set the following values:

set_transient( 'most_recent_user', wp_get_current_user()->user_login, 12 * HOUR_IN_SECONDS )

Here, please pay attention to the following points:

  • I identify the most recent user in the system as the currently logged in user and we store this for 12 hours.
  • Please note that the HOUR_IN_SECONDS constant was introduced in WordPress 3.5. A complete list of constants is available here.

Although this is how we set up transients , this still doesn't explain how we manage transients if they don't exist or already exist.

We will cover this in detail later in this article.

Retrieve Transient

When it comes to retrieving transients, it's very similar to retrieving things like metadata or options. I mean, we just need to know the key to retrieve the information.

So, to be consistent with the example above, we can retrieve the application's most recent user with the following call:

get_transient('most_recent_user');

This will obviously return whatever type of information you have stored, or if the transient has expired (i.e. more than 12 hours have passed), the function will return a boolean of FALSE value.

This is key to remember, especially if you are trying to read cached values ​​and then need to get them from another data source if they are not available in temporary storage.

We'll look at a complete example of doing this before the end of this article.

Delete transient

Finally, if you need to delete a transient to remove it completely, or to remove it before its defined expiration so that it can be replaced with another value, then you can simply use the following function:

delete_transient('most_recent_user');

Additionally, if temporary value deletion is unsuccessful, the function will return FALSE; otherwise, it will return FALSE.

Expiring Transient

When setting the expiration time of a cached value, there are several ways to make setting the value easier than musically basic integer operations.

For example, MINUTE_IN_SECONDS is easier to use than 60, especially when multiplying by minutes, hours, or days.

Starting with WordPress 3.5, several constants have been added to the core application to make these calculations easier to read.

Right now:

  • MINUTE_IN_SECONDS
  • HOUR_IN_SECONDS
  • DAY_IN_SECONDS
  • WEEK_IN_SECONDS
  • YEAR_IN_SECONDS

Easier to use, read and write, isn't it?


Full example using transients

At this point, I think it's important to understand how to set up a transient starting from storing a value in an options table.

Here's the order in which we do this:

  1. We will save an option in the wp_options table.
  2. Next, we will check if the value exists in the cache.
  3. If the value does exist in the cache, we will remove it; otherwise, we will add it.

Then, in the second half of the code, we do the following:

  1. We will try to retrieve the value function from the cache.
  2. If the value exists in the cache, we will fall back to the options table; however, if the value does exist, then we will use it.

With that being said, let’s take a look:

$username = wp_get_current_user()->user_name;
add_option( 'most_recent_user', $username );

// Check to see if the value exists in the cache
if ( FALSE !== get_transient( 'most_recent_user' ) ) {

	// If it does, we'll delete it...
	if( delete_transient( 'most_recent_user' ) ) {

		// ...and store the most recent user for a maximum of one minute
		set_transient( 'most_recent_user', MINUTE_IN_SECONDS );

	} else {
		// The deletion was unsuccessful, so log the error
	}

}

// Now try to read the value from the cache.
if ( FALSE !== ( $username = get_transient( 'most_recent_user' ) ) {

	// Since it doesn't exist, then we'll read it from the option's table
	$username = get_option( 'most_recent_user' );

	// And then we'll update the cache
	set_transient( 'most_recent_user', $username, MINUTE_IN_SECONDS );

}

Please note that this example is not complete - it could be refactored to be clearer and the code should be abstracted into functions more relevant to the application, but the purpose of this code is to show how to handle conditional logic, options and transients .


How does this work with plugins?

Now, with the above in mind, we can revisit the question of how to use transients to improve plug-in performance.

As we mentioned before:

After understanding the available APIs, we will revisit this topic later in this article to understand how they can enhance the performance of cache plugins.

块引用>

Having said that, caching and the WordPress database have to do with the location of the data in the database.

Because transient data is stored in a different location than other data, plugins (such as those based on memcached) will look for the data where the transient data is stored, and then load the data into memory from that location.

So when data is requested, the data will be retrieved from memory. If the data does not exist, it is retrieved from the database.

The most important thing is that if programmed correctly, when reading data from the cache fails and retrieving data from the database, it will be inserted back into the cache so that it will be inserted into the cache the next time it is retrieved. available in memory.

Finally, the key thing to note about transient information is that it has an expiration date. This means that the data will only be stored in that area of ​​the database for a specific period of time.

For this, we need to take this into account. This means that whenever we want to retrieve transients, we need to make sure they exist. If not, we pull them out of their location and store them in the correct location.


Custom query

So far, we have introduced many of the features provided by WordPress related to the basics of web application development.

But we have one last major component to cover, and that is how to handle custom queries.

Of course, there are some great APIs as it relates to running queries designed for the specific purpose of WordPress, such as WP_Query and WP_User_Query, but we also You'll learn about some of the native tools we can write that allow us to make custom queries to the database using defined WordPress objects as well as methods that allow for proper data cleansing.

But we’ll cover all of this and more in the next article.

The above is the detailed content of WordPress Web Application Development Guide: Detailed explanation of available features (Part 7): Caching Technology. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools