»WordPress»WordPress operation cache and cookie example method
These days, because of some problems, I learned about the cache and cookies of WordPress for snacks. I held the big feet of the bag and boiled fish directly, found what I wanted, said good things, simply extracted them directly, mixed them, recorded them here, kept them for record, and reviewed them next time.
WordPress Transients API
Transients means instantaneous. The WordPress Transients API is the simplest method WordPress uses to cache some complex SQL queries and calculation results.It gives these data to be cached an expiration time, and it will be automatically deleted when the time comes. So if you need to store some data with a certain life cycle when you are creating a WordPress plug-in, the Transients API is the best choice.
Where is the data cached by the WordPress Transients API stored
This depends on your server settings. If your server enables object caching such as Memcache, the cached data will be stored in Memcached memory.If it is not enabled, it will be stored in the Options table of the WordPress database.
Functions of WordPress Transients API
As mentioned above, when the server is not started, the data is stored in the Options table, so its interface functions and WordPress'sOption API (get_option, add_option, update_option, delete_option))Basically, the only difference is that the Transients API has an expiration date.So the WordPress Transients API has three similar functions:
Set_transient()//Save a temporary data to the cacheGet_transient()//Get a temporary data from the cacheDelete_transient()//Delete a temporary data from the cache
If you use the get_transient function to obtain a temporary variable that has expired or does not exist, false is returned.In addition, the Transients API will not fill the Options table of the database, because once the temporary variables expire, they will be automatically deleted the next time they are retrieved.
Code example
//Get tag cloudfunction Bing_page_tags(){if( ( $cache = get_transient( 'page_tags_list' ) ) !== False) return $cache;//If there is a Transients cache, return it directly//Start generating HTML code if there is no cache$code = '';if( $tags = get_tags( 'orderby=count&order=DESC' ) ){foreach( $tags as $tag ){$code .= '<li class="tag-box">';$post = current( get_posts( array('tag_id' => $tag->term_id,'posts_per_page' => 1) ) );$code .= "<p class='tag-name'>$tag->name</p>";$code .= sprintf( '<a href="%s">%s</a>', esc_url( get_permalink( $post ) ), get_the_title( $post ) );$code .= '</li>';}$code .= "<ul id='tags_list'>$code</ul>";}//Create Transients cache and return codeSet_transient ('page_tags_list ', $code, DAY_IN_SECONDS);//The cache is valid for 24 hoursreturn $code;}
The above code is used to generate the HTML code of the tag cloud, and cache for 24 hours (DAY_IN_SECONDS is a time constant, representing the number of seconds in 24 hours). If there is a cache, it will be returned directly, without generating again, to avoid a large number of SQL queries.
However, during this period, the modified labels or articles cannot be displayed immediately, so you also need to clear the cache at specific events:
//Clear tag cloud cachefunction clear_page_tags_cache(){delete_transient( 'page_tags_list' );//Delete Transients cache}add_action( 'save_post', 'clear_page_tags_cache' );//Create and edit postsadd_action( 'deleted_post', 'clear_page_tags_cache' );//Delete Articleadd_action( 'created_post_tag', 'clear_page_tags_cache' );//create labeladd_action( 'edited_post_tag', 'clear_page_tags_cache' );//Edit Labeladd_action( 'delete_post_tag', 'clear_page_tags_cache' );//delete a tap
Use WordPress object caching
The following is an example of writing data from related logs to the cache. The current post ID is used as the key, and 'related_post' is used as the group. The cache time is one hour, or 3600 seconds.
global $post;$related_posts_data = wp_get_related_posts();wp_cache_set($post->ID,$related_posts_data,'related_posts',3600);
The above only stores the data in the cache object. When we display related logs, we need to call the object cache to use it. First, check whether there is a cache. If the information you want is not in the cache or has expired.wp_cache_get()It will return false. If so, you need to go to the database to retrieve the information.Otherwise, the information in the cache will be returned.
global $post;$related_posts_data = wp_cache_get($post->ID,'related_posts');if(false === $related_posts_data){$related_posts_data = wp_get_related_posts();wp_cache_set($post->ID,$related_posts_data,'related_posts',3600);}echo $related_posts_data;
Because the data of related logs will become invalid after one hour of setting, there is generally no need to update the cache here. If you change the setting in the background, you need to clear the cache immediately. You can usewp_cache_deleteClean up:
wp_cacache_delete($post->ID,'related_posts');
How to set cookies in WordPress
Cookies are often used when writing WordPress plug-ins and themes, such as accessing user status. Ludou Simple Vote, the plug-in I wrote earlier, uses cookies to record user voting time, so as to achieve simple function of preventing repeated voting. 1. Add the following code in the theme file functions.php to set cookies:
/***The function name and related parameters of the setcookie can be modified by yourself*/function set_newuser_cookie() {if (!isset($_COOKIE['sitename_newvisitor'])) {setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);}}add_action( 'init', 'set_newuser_cookie');//The above line of code can also be changed to the following line of code// add_action('after_setup_theme', 'set_newuser_cookie');
2. Then read the cookie where the cookie value needs to be called
if (isset($_COOKIE['sitename_newvisitor'])) {echo 'Welcome back!';}else {echo 'Hello new visitor!';}
4 Replies to "WordPress operation cache and cookie example method"
God, I used the object cache. It was generated at that time and can be obtained by using wp_cache_get(). But after the execution, the retrieval will become false. What is the reason