If you want to create a custom hook for tracking post views in your WordPress theme, you can follow these steps:
Open your Child Theme’s functions.php File: First Open the functions.php
file located in your theme or child theme’s directory.
Add Custom Function to Create Post Views Meta: Inside the functions.php
file, define a custom function that will be responsible for Creating Post View Meta
. As you can see in this example:
function wpb_create_post_views_meta() {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$posts = get_posts($args);
foreach ($posts as $post) {
add_post_meta($post->ID, 'wpb_post_views_count', '0', true);
}
}
add_action('init', 'wpb_create_post_views_meta');
Add Custom Function to Update Post Views Count: Inside the functions.php
file, define a custom function that will be responsible for updating the post views count. Here’s an example:
function update_post_views_count() {
if (is_singular('post')) {
$post_id = get_the_ID();
$views = get_post_meta($post_id, 'wpb_post_views_count', true);
$views = ($views) ? $views : 0;
$views++;
update_post_meta($post_id, 'wpb_post_views_count', $views);
}
}
add_action('wp', 'update_post_views_count');
In this example, the update_post_views_count
function is hooked to the wp
action, which is triggered on each page load. It checks if the current view is a single post view using is_singular
(‘post’). If it is, it retrieves the current post views count using get_post_meta()
. If the post views count doesn’t exist, it sets it to 0. Then, it increments the count by 1 and updates the post views count meta field using update_post_meta()
.
Display the Post Views Count in Your Theme: Now, you can display the post views count wherever you want in your theme files. Here’s an example of how you can display the post views count within a theme template file, such as single.php
:
<?php
// Get the current post ID
$post_id = get_the_ID();
// Get the post views count
$views = get_post_meta($post_id, 'wpb_post_views_count', true);
// Display the post views count
echo 'Post Views: ' . $views;
?>
In this example, we retrieve the current post ID
using get_the_ID()
. Then, we retrieve the post views count using get_post_meta()
and display it using echo
. You can place this code within the appropriate theme template file (e.g., single.php
) to display the post views count wherever you want it to appear. Remember to save the changes to the functions.php
file. After that, the post views count should be tracked and displayed in your theme.
Please note that you may need to customize this code further based on your specific theme structure and requirements.