Now we need to display post count for each post, for that we need to add custom field in db and it’s value. In WP we use post meta to add any additional information about posts.
So just a basic description of WordPress tables here in image format. Default WordPress has only 12 tables as below.
wp_terms -> Whatever we created as new category name or tag name are going to store here with id.
wp_term_taxonomy -> This is the table where each port terms are defined of which type like it is a category or post_tag or wp_theme etc.
wp_term_relationships -> This is the table where each post is related with different term_texonomy
wp_postmeta -> This is the table where we add custom meta of posts, we are going to add ‘viewcount’ as custom post meta into this table.
Code is simple, we are adding veiwcount of each post very first time and then we will update it on each refresh. To add viewcount and update it is the event which we call on wp_head action hook.
/* Step 8*/
function custom_post_meta_fun()
{
// To use the post id we need to get it as global variable
global $post;
// Check if single post is loading
if (is_single()) {
// echo 'How r you?';
$viewcount = get_post_meta($post->ID, 'viewcount', true);
// echo $viewcount;
// echo var_dump($viewcount);
// if we have not result of viewcount tne add as first view as 1
if ($viewcount == '') {
add_post_meta($post->ID, 'viewcount', 1, true);
} else {
$viewcount++;
update_post_meta($post->ID, 'viewcount', $viewcount);
}
echo get_post_meta($post->ID, 'viewcount', true);
}
}
// when wp head loads, we create/update viewcount for post into the DB
add_action('wp_head', 'custom_post_meta_fun');
And we are displaying viewcount on the list of all post we fetch with shortcode. The git repo is updated there.