php - WordPress,我正在做排名功能,但是如果帖子没有吸引眼球,它会被计算两次
问题描述
<?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 View";
}
return $count.' Views';
}
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_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
?>
我从互联网上复制了这个并将其添加到我的函数 php.ini 中。之后,我也将它包含在我的 home 和 index.php 中。
<div class="related-box original-related wow fadeIn cf animated">
<div class="inbox">
<h2 class="related-h h_ttl">
<span class="gf">ranking</span>
</h2>
<div class="related-post">
<?php
$args = array(
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'ignore_sticky_posts' => 1,
'post__not_in' => $sticky,
'posts_per_page' => 8
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
?>
<li rel="bookmark">
<a href="<?php the_permalink(); ?>" rel="bookmark" class="title no-icon">
<figure class="eyecatch<?php if(!has_post_thumbnail()):?> noimg<?php endif;?>">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'post-thumbnail'); } ?>
</figure>
<h3 class="ttl">
<p>
<?php the_title(); ?>
</p>
<?php echo getPostViews(get_the_ID());
</h3>
</li>
<?php
endwhile;
endif;
wp_reset_postdata();
wp_reset_query();
?>
</div>
</div>
</div>
在single.php的 <?php setPostViews(get_the_ID()); ?>
顶部。
对于大多数帖子,它工作得很好。但对于那些不引人注目的人来说,它是两倍。有人知道为什么吗?我已经尝试了几天解决问题,但仍然没有解决方案,请帮助。
解决方案
推荐阅读
- c - VSCode Intelligence C 扩展不建议有用的词
- c++ - 在 C++ 的子类中使用基类中的运算符重载定义
- node.js - 猫鼬模式参考嵌套数组
- h.264 - 在获得完整视频之前,我可以看到 H.264 视频的开头吗?
- css - 如何在 SCSS 中创建具有 CSS 自定义属性和圆锥渐变的 for 循环?
- angular - Spring,Angular.js 415 不支持的媒体类型错误
- html - 为什么这个使用 .request 的循环逻辑不能正常工作?
- google-sheets - 电子表格列出了不同工作表第一行中所有非空白值的单列
- javascript - 如何使用javascript限制textarea可以动态增加高度和限制最大高度?
- reactjs - 无法通过 HTTPS 使用 SSL 访问 Nginx 后面的 Go Rest API