​​​​​​​​​​​​​​​​​内容简介:

在 WordPress 网站的美化与功能拓展中,添加全网热搜榜单能显著提升网站的吸引力和实用性。今天为大家带来的WordPress主题添加全网热搜榜单教程,任何WordPress网站都可以使用,能让你的网站轻松拥有这一热门功能,助力网站在众多站点中脱颖而出。本教程适用于 WordPress 6.7.2 及相关版本,通过简单的操作,即可自动获取各大平台前十热搜榜。

效果图片:

教程:

1. 将下方的代码保存为 php 文件或者直接下载,例如:rs.php。这一步是整个操作的基础,代码文件的正确保存至关重要。

2. 把保存好的 rs.php 文件放到网站根目录 /wp-content/themes/RiPro/文件夹下。这一操作需谨慎,确保文件放置位置准确无误,否则可能导致后续功能无法正常使用。

3. 进入 WordPress 后台,找到 “页面” 选项,点击 “新页面”。

4. 在页面编辑界面中,选择 “模板”,并在下拉菜单中选择 “聚合热搜” ,然后点击 “保存”。完成这一步后,你的网站页面就会显示出全网热搜榜单。

代码:

<?php

/**
* Template name: 小白博客-聚合热搜
* Description: www.5xb.cn
*/
// 定义需要获取的热搜平台
$platforms = [
'哔哩哔哩', '百度', '知乎', '百度贴吧',
'少数派', 'IT之家', '澎湃新闻', '今日头条',
'36氪', '稀土掘金', '腾讯新闻', '微博'
];

// 缓存文件路径
$cacheDir = __DIR__ . '/cache/';
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0755, true);
}

// 获取热搜数据(带缓存)
function getHotData($platform) {
global $cacheDir;
$cacheFile = $cacheDir . md5($platform) . '.json';
$cacheTime = 10 * 60; // 缓存10分钟,减少API请求频率

// 设置响应头,启用浏览器缓存
header('Cache-Control: public, max-age=300'); // 5分钟浏览器缓存
header('ETag: "' . md5_file($cacheFile) . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($cacheFile)) . ' GMT');

// 检查是否可以返回304 Not Modified
$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;
$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false;

if ($ifNoneMatch && $ifNoneMatch == '"' . md5_file($cacheFile) . '"' ||
$ifModifiedSince && filemtime($cacheFile) <= $ifModifiedSince) {
header('HTTP/1.1 304 Not Modified');
exit;
}

// 如果缓存存在且未过期,直接返回缓存数据
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
return json_decode(file_get_contents($cacheFile), true);
}

// 缓存不存在或已过期,请求新数据
$url = "https://api.pearktrue.cn/api/dailyhot/?title=" . urlencode($platform);

// 优化cURL配置
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_ENCODING, ''); // 启用压缩
curl_setopt($ch, CURLOPT_TCP_FASTOPEN, 1); // 启用TCP Fast Open
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // 优先使用IPv4
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'X-Requested-With: XMLHttpRequest']);
$response = curl_exec($ch);
curl_close($ch);

if ($response) {
$data = json_decode($response, true);
if ($data && isset($data['code']) && $data['code'] == 200) {
// 保存到缓存
file_put_contents($cacheFile, $response);
return $data;
}
}

// 如果请求失败但缓存存在,返回过期的缓存
if (file_exists($cacheFile)) {
return json_decode(file_get_contents($cacheFile), true);
}

return null;
}

// 异步加载标志
$asyncLoad = true;

// 如果是异步请求特定平台数据
if (isset($_GET['platform']) && in_array($_GET['platform'], $platforms)) {
$platform = $_GET['platform'];
$data = getHotData($platform);
if ($data) {
header('Content-Type: application/json');
echo json_encode([
'platform' => $platform,
'data' => $data
]);
exit;
}
}

// 如果不是异步加载,预先获取所有数据
$allData = [];
if (!$asyncLoad) {
foreach ($platforms as $platform) {
$data = getHotData($platform);
if ($data && isset($data['data']) && $data['code'] == 200) {
$allData[$platform] = [
'title' => $data['title'],
'subtitle' => $data['subtitle'],
'updateTime' => $data['updateTime'],
'items' => array_slice($data['data'], 0, 10) // 只取前10条
];
}
}
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Cache-Control" content="public, max-age=3600">
<link rel="icon" href="https://www.5xb.cn/wp-content/themes/ripro-v5/assets/img/favicon.png" type="image/png">
<link rel="preconnect" href="https://api.pearktrue.cn">
<title>全网热搜榜 - 小白博客</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
background-color: #f5f7fa;
color: #333;
overflow-x: hidden;
}

.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}

header {
text-align: center;
margin-bottom: 30px;
padding: 20px 0;
}

h1 {
font-size: 2.5rem;
color: #2c3e50;
margin-bottom: 10px;
}

.subtitle {
font-size: 1rem;
color: #7f8c8d;
}

.row {
display: flex;
flex-wrap: wrap;
margin: 0 -15px 30px;
}

.platform {
flex: 0 0 calc(25% - 30px);
margin: 0 15px 30px;
background: rgba(255, 255, 255, 0.9);
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
overflow: hidden;
transform: translate3d(0, 0, 0);
transition: transform 0.3s, box-shadow 0.3s;
min-height: 400px;
contain: content;
}

.platform:hover {
transform: translateY(-5px);
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.platform-header {
padding: 15px 20px;
background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
color: white;
position: relative;
}

.platform-title {
font-size: 1.2rem;
font-weight: bold;
margin-bottom: 5px;
}

.platform-subtitle {
font-size: 0.8rem;
opacity: 0.8;
}

.platform-time {
font-size: 0.7rem;
position: absolute;
right: 15px;
bottom: 10px;
opacity: 0.8;
}

.hot-list {
padding: 15px;
}

.hot-item {
padding: 10px 15px;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
}

.hot-item:last-child {
border-bottom: none;
}

.hot-rank {
width: 24px;
height: 24px;
line-height: 24px;
text-align: center;
border-radius: 4px;
margin-right: 10px;
font-weight: bold;
font-size: 0.8rem;
}

.rank-1, .rank-2, .rank-3 {
color: white;
}

.rank-1 {
background-color: #ff4757;
}

.rank-2 {
background-color: #ff6b81;
}

.rank-3 {
background-color: #ff7f50;
}

.rank-other {
background-color: #f1f2f6;
color: #747d8c;
}

.hot-title {
flex: 1;
font-size: 0.9rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.hot-title a {
color: #2c3e50;
text-decoration: none;
transition: color 0.2s;
}

.hot-title a:hover {
color: #3498db;
}

footer {
text-align: center;
padding: 20px 0;
color: #7f8c8d;
font-size: 0.9rem;
}

.loading {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
color: #7f8c8d;
}

.loading-spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin-right: 10px;
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

/* 背景漂浮特效 - 减少数量和简化动画 */
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
overflow: hidden;
pointer-events: none;
}

.bubble {
position: absolute;
border-radius: 50%;
background: linear-gradient(135deg, rgba(106, 17, 203, 0.1) 0%, rgba(37, 117, 252, 0.1) 100%);
animation: float 20s infinite ease-in-out;
will-change: transform, opacity;
}

@keyframes float {
0% {
transform: translate3d(0, 0, 0) rotate(0deg);
opacity: 1;
}
100% {
transform: translate3d(0, -1000px, 0) rotate(720deg);
opacity: 0;
}
}

@media (max-width: 1200px) {
.platform {
flex: 0 0 calc(33.333% - 30px);
}
}

@media (max-width: 992px) {
.platform {
flex: 0 0 calc(50% - 30px);
}
}

@media (max-width: 576px) {
.platform {
flex: 0 0 calc(100% - 30px);
}
}
</style>
</head>
<body>
<div class="background" id="background"></div>

<div class="container">
<header>
<h1>全网热搜榜</h1>
<div class="subtitle">实时掌握全网热点</div>
</header>

<?php
// 每行显示4个平台,共3行
$chunks = array_chunk($platforms, 4);
foreach ($chunks as $rowPlatforms) {
echo '<div class="row">';
foreach ($rowPlatforms as $platform) {
echo '<div class="platform" id="platform-' . md5($platform) . '" data-platform="' . htmlspecialchars($platform) . '">';

if ($asyncLoad) {
// 异步加载时显示加载中
echo '<div class="platform-header">';
echo '<div class="platform-title">' . htmlspecialchars($platform) . '</div>';
echo '<div class="platform-subtitle">加载中...</div>';
echo '</div>';
echo '<div class="loading"><div class="loading-spinner"></div>正在加载...</div>';
} else if (isset($allData[$platform])) {
// 非异步加载,直接显示数据
$data = $allData[$platform];
$updateTime = new DateTime($data['updateTime']);
$updateTime->setTimezone(new DateTimeZone('Asia/Shanghai'));
$formattedTime = $updateTime->format('Y-m-d H:i');

echo '<div class="platform-header">';
echo '<div class="platform-title">' . htmlspecialchars($data['title']) . '</div>';
echo '<div class="platform-subtitle">' . htmlspecialchars($data['subtitle']) . '</div>';
echo '<div class="platform-time">更新时间: ' . $formattedTime . '</div>';
echo '</div>';

echo '<div class="hot-list">';
foreach ($data['items'] as $index => $item) {
$rankClass = $index < 3 ? 'rank-' . ($index + 1) : 'rank-other';
echo '<div class="hot-item">';
echo '<div class="hot-rank ' . $rankClass . '">' . ($index + 1) . '</div>';

// 处理不同平台的链接格式
$url = isset($item['url']) ? $item['url'] : '#';
if ($platform == '哔哩哔哩' && isset($item['id'])) {
$url = 'https://www.bilibili.com/video/' . $item['id'];
}

$title = isset($item['title']) ? $item['title'] :
(isset($item['word']) ? $item['word'] :
(isset($item['name']) ? $item['name'] : '未知标题'));

echo '<div class="hot-title"><a href="' . $url . '" target="_blank">' . htmlspecialchars($title) . '</a></div>';
echo '</div>';
}
echo '</div>';
}

echo '</div>';
}
echo '</div>';
}
?>

<footer>
<p>© <?php echo date('Y'); ?> 全网热搜榜 - 数据来源于各大平台</p><br>
<p>小白博客版权所有</a></p>
</footer>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
// 创建背景漂浮气泡 - 使用文档片段优化性能
const createBubbles = () => {
const background = document.getElementById('background');
const fragment = document.createDocumentFragment();
const bubbleCount = 8;

for (let i = 0; i < bubbleCount; i++) {
const bubble = document.createElement('div');
bubble.classList.add('bubble');

// 使用transform替代width/height以减少重排
const size = Math.random() * 100 + 50;
bubble.style.transform = `scale(${size/100})`;

// 使用transform替代left/bottom以提高性能
const x = Math.random() * 100;
const y = Math.random() * 100 - 20;
bubble.style.transform += ` translate(${x}vw, ${y}vh)`;

// 随机动画延迟和持续时间
const duration = Math.random() * 20 + 15;
const delay = Math.random() * 10;
bubble.style.animationDuration = `${duration}s`;
bubble.style.animationDelay = `${delay}s`;

fragment.appendChild(bubble);
}

background.appendChild(fragment);
};

// 使用requestIdleCallback延迟加载背景特效
if ('requestIdleCallback' in window) {
requestIdleCallback(createBubbles);
} else {
setTimeout(createBubbles, 500);
}

<?php if ($asyncLoad): ?>
// 异步加载各平台数据
const loadPlatformData = (platformElement) => {
const platform = platformElement.getAttribute('data-platform');

fetch(`?platform=${encodeURIComponent(platform)}`, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
credentials: 'same-origin'
})
.then(response => response.json())
.then(result => {
if (result && result.data) {
const data = result.data;

// 更新平台头部
let updateTime = new Date(data.updateTime);
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
};
const formattedTime = updateTime.toLocaleString('zh-CN', options);

let headerHTML = `
<div class="platform-title">${data.title}</div>
<div class="platform-subtitle">${data.subtitle}</div>
<div class="platform-time">更新时间: ${formattedTime}</div>
`;

platformElement.querySelector('.platform-header').innerHTML = headerHTML;

// 创建热搜列表
let hotListHTML = '<div class="hot-list">';
const items = data.data.slice(0, 10); // 只取前10条

items.forEach((item, index) => {
const rankClass = index < 3 ? `rank-${index + 1}` : 'rank-other';

// 处理不同平台的链接格式
let url = item.url || '#';
if (platform === '哔哩哔哩' && item.id) {
url = `https://www.bilibili.com/video/${item.id}`;
}

const title = item.title || item.word || item.name || '未知标题';

hotListHTML += `
<div class="hot-item">
<div class="hot-rank ${rankClass}">${index + 1}</div>
<div class="hot-title"><a href="${url}" target="_blank">${title}</a></div>
</div>
`;
});

hotListHTML += '</div>';

// 替换加载中的内容
platformElement.querySelector('.loading').remove();
platformElement.insertAdjacentHTML('beforeend', hotListHTML);
}
})
.catch(error => {
console.error(`加载 ${platform} 数据失败:`, error);
platformElement.querySelector('.loading').innerHTML = '加载失败,请刷新重试';
});
};

// 使用 Intersection Observer 实现懒加载
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadPlatformData(entry.target);
observer.unobserve(entry.target); // 加载后不再观察
}
});
}, {
rootMargin: '200px', // 提前200px开始加载
threshold: 0.1
});

// 观察所有平台元素
document.querySelectorAll('.platform').forEach(platform => {
observer.observe(platform);
});
<?php endif; ?>
});
</script>
</body>
</html>