Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
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? –  pixelngrain Oct 11 '12 at 15:12
    
I found one tutorial.. thanks –  pixelngrain Oct 12 '12 at 12:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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