1. Thoughts
I thought at first that I should Is there any plug-in that can achieve this? After searching, the first one isPost Views Counter
.
Before installing this plug-in, I thought about it, can I implement it myself? After all, if you put your hands into it, you will gain something.
Before searching, what I thought of was to add a field to thewp_post
table, and then save the data when the article is opened, so that the reading count of the article can be saved persistently.
But WordPress is written in PHP and MySQL adds fields, which is quite time-consuming for me on the front end. For example, how to operate the database using PHP, and how to add fields using PHP? It is estimated that it will take at least half a day or even a day to complete.
Is there an easier way?
Because I have messed with the wordpress database before, I know what tables there are. So it suddenly occurred to me that there is awp_postmeta
table. From the literal point of view, it should be possible to add a field or start from this table.
meta_id is the id, post_id is the article id, meta_key and meta_value are the key-value pair information of the article.
2. Methods provided by wordpress
How to operate this table?
wordpress provides several methods:
add_post_meta($post_id, $meta_key, $meta_value, $unique); get_post_meta($post_id, $meta_key, $single); update_post_meta($post_id, $meta_key, $meta_value, $prev_value); delete_post_meta($post_id, $meta_key, $meta_value);
3. Specific code implementation
How to use it?
First add the function encapsulation of add and get in thefunction.php
file, and then call it in thetemplate-parts/content-single.php
file.
// function.php function addPostViews($postId) { $key = 'post_views'; $value = get_post_meta($postId, $key, true); if($value == ''){ $value = 0; delete_post_meta($postId, $key); add_post_meta($postId, $key, $value); }else{ $value++; update_post_meta($postId, $key, $value); } } function getPostViews($postId){ $key = 'post_views'; $value = get_post_meta($postId, $key, true); if($value == ''){ $value = 0; delete_post_meta($postId, $key); add_post_meta($postId, $key, $value); return $value; } return $value; } // template-parts/content-single.php阅读: