• Resolved kirasiris

    (@kirasiris)


    The code is not mine, I found it in a Youtube tutorial.
    What I want is to display the number of views a post has, but just by clicking and entering into the post.
    The function that I have adds a view every time I refresh the page, so why would it add a view if I yet have not clicked on the post?
    Can anyone help me to solve this?

    This is what I have in my functions file

    
    // Views per post/page
    //// Add counts views per post by refreshing(F5) the current post
    //Set the Post Custom Field in the WP dashboard as Name/Value pair 
    function addview($post_ID) {
     
        //Set the name of the Posts Custom Field.
        $count_key = 'post_views_count'; 
         
        //Returns values of the custom field with the specified key from the specified post.
        $count = get_post_meta($post_ID, $count_key, true);
         
        //If the the Post Custom Field value is empty. 
        if($count == ''){
            // $count = 0; // set the counter to zero.
             
            //Delete all custom fields with the specified key from the specified post. 
            delete_post_meta($post_ID, $count_key);
             
            //Add a custom (meta) field (Name/value)to the specified post.
            add_post_meta($post_ID, $count_key, '0');
            return $count . ' View';
         
        //If the the Post Custom Field value is NOT empty.
        }else{
            $count++; //increment the counter by 1.
            //Update the value of an existing meta key (custom field) for the specified post.
            update_post_meta($post_ID, $count_key, $count);
             
            //If statement, is just to have the singular form 'View' for the value '1'
            if($count == '1'){
            return $count . ' View';
            }
            //In all other cases return (count) Views
            else {
            return $count . ' Views';
            }
        }
    }
    

    and this what I have in my index and single files:
    <?php if(function_exists('addview')) { echo addview(get_the_ID()); }?>

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Show Count per view in Post’ is closed to new replies.