我很难使用this snippet 每次查询帖子时,我都会收到双重视图。
这是我的职责。php文件:
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);
然后我放置
setPostViews(get_the_ID());
进入我在归档中循环的模板部分。php如下所示:
<?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; ?>
这是我的ad.php文件:
<?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=adClickCounter&id="+<?php echo $post->ID?>,
success: function() {
window.setTimeout(function(){
window.open("<?php echo $reDirectUrl; ?>","_blank")
}, 50);
}
});
});
});
</script>