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?