首页 > 解决方案 > 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()); ?> 顶部。

对于大多数帖子,它工作得很好。但对于那些不引人注目的人来说,它是两倍。有人知道为什么吗?我已经尝试了几天解决问题,但仍然没有解决方案,请帮助。

标签: phpwordpress

解决方案


推荐阅读