Double count view in archive.php
I'm having a hard time using this snippet I'm getting double views each time the post is queried.
This is in my functions.php file:
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
Then I places setPostViews(get_the_ID());
into a template part that i loop in the archive.php like this:
?php
$term = $wp_query-queried_object;
$args=array(
'post_type' = 'anuncio',
'posts_per_page' = 1,
'orderby' = 'rand',
'tax_query' = array(
array(
'taxonomy' = 'ciudad',
'field' = 'slug',
'terms' = $term-slug,
),
),
'meta_query' = array(
array(
'key' = '_adStatus',
'value' = 'activo'
)
),
);
$loop = new WP_Query( $args );
while ( $loop-have_posts() ) : $loop-the_post(); ?
?php get_template_part('templates/ads/ad'); ?
?php endwhile; ?
This is my ad.php file:
?php
$adID = $post-ID;
$attachment_id = get_post_thumbnail_id( $adID );
$size = "grid-cover";
$image = wp_get_attachment_image_src( $attachment_id, $size );
$url = $image[0];
setPostViews($adID);
?
a href="#" class="ad ?php echo $post-ID; ? lazyBackground" data-background="?php echo $url; ?"
p class="h2 ad-title"?php the_title(); ?/p
p?php echo get_the_content(); ?/p
form method="post" id="?php echo $post-ID; ?clickCounter" class="hidden"
input type="submit" class="?php echo $post-ID; ?"
/form
/a
script
jQuery(document).ready( function() {
jQuery('.ad.?php echo $post-ID; ?').click(function() {
jQuery('#?php echo $post-ID; ?clickCounter').submit();
});
jQuery('#?php echo $post-ID; ?clickCounter').submit(function(e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: "action=adClickCounterid="+?php echo $post-ID?,
success: function() {
window.setTimeout(function(){
window.open("?php echo $reDirectUrl; ?","_blank")
}, 50);
}
});
});
});
/script