I am very new to WordPress plugin development.
I have been searching this for a quite a while now but I am currently creating a plugin and I need my plugin to start logging the amount of views a post has had. I already know what I want this part of to do however I am having trouble find out how to a PHP function for when a post is viewed by a visitor to my WordPress site.
Could someone please show me what the WordPress hook/event is to run a function on post view/load? I want to do this without the use of template as well.
1 Answer
I assume you are looking for a conditional to check if you are on a post page.
You can do so by using is_single()
:
if (is_single()) {
// Update your post views here
}
If you insist on using filters or hooks, you can use the_content
filter:
add_filter( 'the_content', 'update_post_views' );
function update_post_views($content){
if (is_single()) {
$id = get_the_ID();
// Now update your post's views
}
return $content;
}