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

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

// REST API: 文章阅读数
add_action('rest_api_init', function () {
    register_rest_route('zke/v1', '/post-views/(?P<id>\d+)', array(
        'methods'             => 'GET',
        'callback'            => 'zke_get_post_views',
        'permission_callback' => '__return_true',
    ));
});

function zke_get_post_views($data) {
    $post_id = absint($data['id']);
    $views   = (int) get_post_meta($post_id, 'views', true);
    return rest_ensure_response(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)) :
        $post_id = get_the_ID(); // 或 $post->ID
        
        // 1. 【关键】预取当前阅读数,填入静态 HTML
        $initial_views = get_post_meta($post_id, 'views', true);
        if (!$initial_views) $initial_views = 0;
        $formatted_initial = number_format($initial_views);
        
        // 2. 使用唯一 ID(避免循环冲突)
        $element_id = 'views-count-' . $post_id;
        $rest_url = rest_url('zke/v1/post-views/') . $post_id;
        ?>
        <span class="dot">•</span>
        <span id="<?php echo esc_attr($element_id); ?>"><?php echo esc_html($formatted_initial); ?></span>
        <span>阅读</span> <!-- 你也可以调整文字顺序,这里保持原有结构 -->
        
        <script>
            (function() {
                var container = document.getElementById('<?php echo esc_js($element_id); ?>');
                if (!container) return;
                
                // 3. 页面加载完成后,异步获取最新阅读数(静默更新)
                document.addEventListener('DOMContentLoaded', function() {
                    fetch('<?php echo esc_url($rest_url); ?>?t=' + Date.now())
                        .then(response => {
                            if (!response.ok) throw new Error('Network response was not ok');
                            return response.json();
                        })
                        .then(data => {
                            if (typeof data.views === 'number' && data.views != <?php echo intval($initial_views); ?>) {
                                container.innerText = Number(data.views).toLocaleString();
                            }
                        })
                        .catch(function(error) {
                            // 4. 静默失败,保留预填的初始值,不影响用户
                            console.warn('Views update failed:', error);
                        });
                });
            })();
        </script>
    <?php endif; ?>
<?php endif; ?>

 

本文作者:ZKCOI

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

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

本站资源仅供个人学习和交流,如若转载,请注明出处,详见《免责声明》

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
ZKCOIZKCOI
感谢LLSVPs​这位大V的引用
上一篇 2024年1月15日 下午7:26
将新品打造成爆品,种草—投流—直播
下一篇 2024年1月16日 上午8:54

相关推荐

发表回复

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

联系博主

立即联系
一般有空就回复

qrcode_web

微信扫码联系我

insert_link 友情链接
分享本页
返回顶部