I want to update a custom field value whenever an Editor visits a post.
I want to get it done to track hits on a post by editors on my site.
Not finding a proper solution or I am confused with multiple solutions.
I think I can use update_post_meta() on single post page but not sure if it is a right solution.
1 Answer
Something like this should do:
function track_editor_wpse_108606() {
if (is_single()) {
$current_user = wp_get_current_user();
if (user_can( $current_user, 'editor' )) {
global $post;
$current = get_post_meta($post->ID,'editor_tracker',true);
$current = (!empty($current)) ? $current + 1 : 1;
update_post_meta($post->ID,'editor_tracker',$current);
}
}
}
add_action('wp_head','track_editor_wpse_108606');
This is not especially efficient. You are reading and writing to the database for these page loads. You could improve this by means of a direct SQL query if you want to go that somewhat risky route, and could improve it further by using Javascript to insert the value if you don't mind that it won't work if the user disables Javascript.
if()condition withcurrent_user_can('editor'). Hope that will light you to a good solution.