0

I am trying to add simple view counter for my advert and everything seems works fine with below code but only it is inserting each time new row on post "Update". What I want if the post id is exists than it should not add or modify anything into that table just ignore so view counter will use same row instead of multiple row of

Function to insert row on publish or update

function get_publishing_id($post_id) {
    global $wpdb;

    $post= get_post($post_id);
    if ($post->post_type == 'post'
      && $post->post_status == 'publish') {

        if(empty ($counter)) {

            $counter = 1;

            $wpdb->insert( 
                $wpdb->prefix . 'advert_views', 
                array( 
                    'postid' => $post->ID,
                    'view_count' => $counter,
                ),
                array(
                    '%d',
                    '%d'
                )
            );          
        }

    } // end if
} // end function
add_action('save_post','get_publishing_id');

Function to update table on view

function update_counter($post_id){

    global $wpdb;

    $query = "SELECT view_count FROM ".$wpdb->prefix."advert_views WHERE postid = $post_id";

    $query_run = mysql_query($query);

    if(mysql_num_rows($query_run) > 0) {

        $count = mysql_result($query_run, 0, 'view_count' );

        $count_inc = $count + 1;

        $query_update = "UPDATE ".$wpdb->prefix."advert_views SET view_count = $count_inc WHERE postid = $post_id";
        @$query_update_run = mysql_query($query_update);        
    }

}

Also one more thing I want to know in function udaate_counter() do I need to have @$query_update_run = mysql_query($query_update); or can be use alternate way?

1 Answer 1

2

why use a custom table for this? eliminate the whole save_post function and just use get_post_meta and update_post_meta to check/increment the view count. this is exactly what post meta data is for.

1
  • Wow! I think this can be nice solution. However can you please help me by adding some more details in your suggestion? Some hint how can I use post meta to increment on each view? Just for knowledge this function I am using on archive index not on single.php so will it work for that too? Commented Oct 11, 2012 at 15:12

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.