A, ideas,
At first, I thought of what kind of plug-in I should be able to implement. I searched it, and the first thing I saw was Post Views Counter.
Before installing the plug-in, I wondered if I could implement it myself. After all, there will be a harvest.
Before the search, I thought of adding a field to the WP_POST table, and then storing the data when the article is opened, so that I can persist the number of articles read. But WordPress uses PHP to write, MySQL plus fields, for me in the front end, or more time consuming. For example, how to use PHP to manipulate the database, how to use PHP to add fields? Estimated at least half a day or even a day of time, to finish.
Is there an easier way?
Because I’ve played around with WordPress databases before, I know what kind of tables there are. So it occurred to me that there was awp_postmeta
Table. Literally, it should be possible to add a field or start with the table.
Meta_id is the id, post_id is the id of the article, and meta_key and meta_value are the key and value pairs of the article.
Second, WordPress provides methods
So how do you manipulate 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);
Three, specific code implementation
So how does it work? First add the function encapsulation of add and get in the function.php file, and then make the call in the template-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 <p> php echo getPostViews(get_the_ID()); ? ></p> <? php addPostViews(get_the_ID()); ? >