I'm trying to count rows in sql table using SELECT COUNT(*) for the post view count. My code is

    function get_post_views($offset=0, $post_id){
        global $wpdb;
        $get_visit_query = "SELECT COUNT(*) FROM {$wpdb->prefix}" . VISITS_TABLE .   " WHERE object_id = '{$post_id}' AND datetime > '2021-09-07 0:0:0' AND datetime < '2021-09-09 0:0:0'";
        $visits_total =  $wpdb->get_var( $get_visit_query, 0 );

        $combined_views = (int)$get_visit_query + (int)$offset;

        return $combined_views;}

And if I get the rows count value($combined_views) from VISITS_TABLE, I will change the meta_value in wp_post_meta table with the code

     function set_post_views($offset=0, $post_id) {
        $visits_total = apply_filters('get_post_views', $offset, $post_id);

        update_post_meta($post_id, POST_VIEW_COUNT_KEY, $visits_total); 

The problem is that the meta_value is 0 all the time. (Post view count is 0 all the time)
I tried this tread, but didn't work for me sadly.

  • What is VISITS_TABLE? That's not WP core.
    – vancoder
    Commented Apr 26, 2022 at 22:04

1 Answer 1

 $combined_views = (int)$get_visit_query + (int)$offset;

This doesn't make much sense. $get_visit_query is a string (your query). Converting it to int returns in 0, see this snippet. Instead it should be

$combined_views = (int)$visits_total + (int)$offset;

Sidenote: Are you actually hooking the function via add_filter()? If not, apply_filters('get_post_views', ..) will not have the desired effect. Using the function name doesn't magically add it to the filters, you need to explicitly define it e.g. via add_filter('get_post_views', 'get_post_views', 10, 2);.

  • Thanks for the advice @kero and I have applied what you asked me to do but doesn't work either. I changed the code to $combined_views = (int)$visits_total + (int)$offset; as you said and defined add_filter('get_post_views', array($this, 'get_post_views'), 10, 2); above but no changed.. Commented Apr 18, 2022 at 5:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.