You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中实现REST API数据的实时计数器更新

实现实时动态计数器展示API数据需求

我正在使用wp-get api插件调用一个公开REST API,该API返回的数据持续变化。希望无需手动调用API或刷新页面,就能在id为heart的容器中以计数器动态跳动的方式展示这些实时数据。当前实现代码如下:

<div class="box"  id="heart">
  <div class="glass"></div>
    <div class="content">
      <h1><?php
              $data = wpgetapi_endpoint( 'yahoo', 'yahoo', array('debug' => false) );
              $result = intval($data["tabsOpened"]/15);
              echo $result;
            ?> 
        </h1> 
        <p>Food Plates Donated</p>  
     <h1><?php
              $data = wpgetapi_endpoint( 'yahoo', 'yahoo', array('debug' => false) );
              $result = intval($data["tabsOpened"]);
              echo $result;
            ?> 
        </h1> 
        <p>Tabs Opened</p>  
  </div>
</div>

解决方案

要实现这个需求,需结合前端定时请求API和数字平滑过渡动画两个核心部分,具体步骤如下:

1. 重构HTML结构,给动态元素添加唯一标识

为需要更新的数字元素添加ID,方便JavaScript定位操作:

<div class="box" id="heart">
  <div class="glass"></div>
  <div class="content">
    <h1 id="food-plates"></h1> 
    <p>Food Plates Donated</p>  
    <h1 id="tabs-opened"></h1> 
    <p>Tabs Opened</p>  
  </div>
</div>

2. 搭建WordPress自定义REST接口

前端直接请求第三方API易出现跨域问题,通过WordPress自定义接口转发请求:

// 将以下代码添加到主题的functions.php文件中
add_action('rest_api_init', function () {
  register_rest_route('custom/v1', '/yahoo-data/', array(
    'methods' => 'GET',
    'callback' => 'get_yahoo_api_data',
    'permission_callback' => '__return_true' // 设置为公开访问
  ));
});

function get_yahoo_api_data() {
  $data = wpgetapi_endpoint('yahoo', 'yahoo', array('debug' => false));
  // 预处理数据后返回
  return array(
    'foodPlates' => intval($data["tabsOpened"] / 15),
    'tabsOpened' => intval($data["tabsOpened"])
  );
}

3. 前端JS实现定时请求与数字动画

用JavaScript定时调用自定义接口,同时实现数字从当前值平滑过渡到新值的动画效果:

// 获取页面中的数字元素
const foodPlatesEl = document.getElementById('food-plates');
const tabsOpenedEl = document.getElementById('tabs-opened');

// 数字过渡动画函数:从当前值平滑跳转到目标值
function animateCounter(element, targetValue, duration = 1000) {
  const currentValue = parseInt(element.textContent) || 0;
  const increment = (targetValue - currentValue) / (duration / 16); // 按60帧率计算步长
  let current = currentValue;

  const timer = setInterval(() => {
    current += increment;
    // 到达目标值时停止动画
    if ((increment > 0 && current >= targetValue) || (increment < 0 && current <= targetValue)) {
      current = targetValue;
      clearInterval(timer);
      // 可选:添加跳动视觉反馈
      element.classList.add('count-jump');
      setTimeout(() => element.classList.remove('count-jump'), 200);
    }
    element.textContent = Math.floor(current);
  }, 16);
}

// 请求数据并更新页面
function fetchAndUpdateData() {
  fetch('/wp-json/custom/v1/yahoo-data/')
    .then(response => response.json())
    .then(data => {
      animateCounter(foodPlatesEl, data.foodPlates);
      animateCounter(tabsOpenedEl, data.tabsOpened);
    })
    .catch(error => console.error('数据请求失败:', error));
}

// 页面加载时执行一次,之后每30秒自动刷新(可根据需求调整间隔)
document.addEventListener('DOMContentLoaded', () => {
  fetchAndUpdateData();
  setInterval(fetchAndUpdateData, 30000);
});

4. 可选:添加CSS增强跳动视觉效果

如果需要更明显的"跳动"反馈,添加以下CSS样式:

#food-plates, #tabs-opened {
  transition: transform 0.2s ease;
}

.count-jump {
  transform: scale(1.1);
}

内容的提问来源于stack exchange,提问作者Prince Bhati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:03:18