Memcached memory caching can optimize many functions of WordPress and make your WordPress faster. The following column WordPress Tutorial will introduce how to use Memcached to deeply optimize WordPress.
Use memory cache to optimize WordPress article browsing statistics efficiency.
WordPress default custom field caching method
General article browsing statistics plug-ins use custom fields to store data. If the server is turned on With Memcached memory cache, how is the data of custom fields cached? WordPress will use $post_id as the cache_key and 'post_meta' as the cache_group as a whole for caching.
So updating a custom field is equivalent to updating the cache of all custom fields under the $post_id together, and each time the article is viewed, the custom field data will be incremented by 1, so that every time The cache of custom fields will be updated, which will result in three more SQL queries for each page.
Use memory cache to optimize article browsing statistics efficiency
Is there any way to solve this problem? We can cache the browsing statistics of the article in the memory first, and then write it to the database after adding 10 views each time. This can greatly reduce the number of SQL queries caused by changes in custom fields in WordPress operations.
Copy the above code into the functions.php file of the current theme:
// 更新文章浏览数的时候,首先更新到内存中,然后每10次,才写到数据库中 add_filter('update_post_metadata', function($check, $post_id, $meta_key, $meta_value){ if($meta_key == 'views'){ if($meta_value % 10 != 0){ $check= true; wp_cache_set($post_id, $meta_value, 'views'); }else{ wp_cache_delete($post_id, 'views'); } } return $check; }, 1, 4); // 获取文章浏览数的时候,首先从内存中获取,没有才从数据库中获取 add_filter('get_post_metadata', function($pre, $post_id, $meta_key){ if($meta_key == 'views'){ $views= wp_cache_get($post_id, 'views'); if($views !== false){ return [$views]; } } return $pre; }, 1, 3);
There may also be a small problem: Since Memcached's cache is not persistent, if you accidentally cache the memory If cleared, part of the number of article views will be lost, but it will definitely be less than 10.
The WPJAM Basic plug-in has integrated Memcached. After downloading WPJAM Basic, copy the object-cache.php file in the wpjam-basic/template/ directory to the wp-content directory.
The above is the detailed content of Use memory caching to optimize WordPress article browsing statistics efficiency. For more information, please follow other related articles on the PHP Chinese website!