The proper way would be to check if you are on a single page, and if so, then check if your post has the oznamy
set as one of its categories.
Let’s rewrite your code the following way:
if ( is_single() && in_category( 'oznamy' , get_the_ID() ) ) {
// Get the current user
$current_user = wp_get_current_user();
$currentuserid = $current_user->ID;
// Update the post's meta
update_post_meta($post->ID , 'userid:'.$currentuserid , $post->ID);
}
Important notes
- This code should be used in
functions.php
instead of directly being used in the template files - You might be visiting another post by accident, that causes to save metadata for that post too. You didn’t post your
single.php
‘s content, so I can’t tell if you have another post being loaded aside. - You should use
update_post_meta
instead ofadd_post_meta
unless you want to end up with a million of metadata saved on each visit. - There is a second argument possible to be set in the
in_category()
function, which is the post’s ID. This might solve your problem, by only setting the current post’s ID.is_single()
also accepts the same argument.