ajax获取阅读数防止无法刷新阅读数

突然发现justnews这个主题的阅读数无法更新,排查后发现是使用了静态缓存和CDN导致的,考虑通过rest api使用ajax在文章页面更新。于是在子主题里把父主题single复制过来,重新改了下,完美解决。

//首先注册一个rest api
add_action('rest_api_init', function () {
    register_rest_route('zke/v1','/post-views/(?P\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_post_views',
        'permission_callback' => 'rest_allow_all_users',
    ));
});

function rest_allow_all_users() {
    return true;
}

function get_post_views($data) {
    $post_id = $data['id'];
    $views = (int) get_post_meta($post_id, 'views', true);
    
    return array(
        'views' => $views,
    );
}




//然后在文章页用ajax
<?php
    if (function_exists('the_views')) {
        $views_options = get_option('views_options');
        if (is_array($views_options) && function_exists('should_views_be_displayed') && should_views_be_displayed($views_options)) {
            ?>
            <span class="dot">•</span>
            <span id="views-count"></span>
            <script>
                // 使用 REST API 获取最新阅读量
                document.addEventListener('DOMContentLoaded', function () {
                    var postId = <?php echo $post->ID; ?>;
                    fetch('<?php echo rest_url('zke/v1/post-views/'); ?>' + postId)
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('views-count').innerText = '阅读 ' + data.views;
                        })
                        .catch(error => console.error('Error fetching views:', error));
                });
            </script>
            <?php
        }
    }
    ?>

 

本文作者:𝙕𝙆𝘾𝙊𝙄

文章名称:ajax获取阅读数防止无法刷新阅读数

文章链接:https://www.zkcoi.com/365up/program/3100.html

本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
𝙕𝙆𝘾𝙊𝙄𝙕𝙆𝘾𝙊𝙄
上一篇 2024年1月15日 下午7:26
下一篇 2024年1月16日 上午8:54

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

私聊博主

立即联系
一般有空就回复

qrcode_web

微信扫码联系我

分享本页
返回顶部