文章最后更新时间:
![图片[1]-子比美化-添加随机访问文章功能-九二分享](https://oss.xkzhi.cn/2025/06/28/xeo5ry.gif)
如果喜欢的话下面是教程
功能教程
首先我们打开自己网站根目录
/**
* 开始-注册自定义API端点用于随机文章跳转
*/
function register_random_post_redirect_endpoint() {
register_rest_route('wp/v2', '/random-post', array(
'methods' => 'GET',
'callback' => 'handle_random_post_redirect',
'permission_callback' => '__return_true'
));
}
add_action('rest_api_init', 'register_random_post_redirect_endpoint');
function handle_random_post_redirect($request) {
// 获取所有已发布的文章
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'fields' => 'ids',
'posts_per_page' => -1,
);
$posts = get_posts($args);
if (empty($posts)) {
return new WP_Error('no_posts', '没有找到文章', array('status' => 404));
}
// 随机选择一篇文章
$random_post_id = $posts[array_rand($posts)];
$random_post_url = get_permalink($random_post_id);
// 直接重定向
if (!headers_sent()) {
wp_redirect($random_post_url);
exit;
}
// 如果无法重定向,返回JSON响应
return array(
'post_id' => $random_post_id,
'post_url' => $random_post_url,
'message' => '请手动访问上面的URL'
);
}
function zib_get_random_post_button($args = array()) {
if (!_pz('random_post_button', true)) {
return '';
}
$random_icon = '<svg t="1751112388719" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5410" width="1000" height="1000" data-spm-anchor-id="a313x.search_index.0.i12.4dfa3a81Mc8lKy"><path d="M166.464 448.704l212.64 128.736a32 32 0 1 1-33.152 54.72L79.424 470.848a32 32 0 0 1 4.256-56.928l832-347.456a32 32 0 0 1 43.744 35.52l-145.76 768a32 32 0 0 1-48.576 21.056L494.88 719.712a32 32 0 0 1 34.24-54.08l230.464 146.112L885.44 148.48 166.464 448.704z" p-id="5411" data-spm-anchor-id="a313x.search_index.0.i14.4dfa3a81Mc8lKy"></path><path d="M416 632.096V896a32 32 0 0 1-64 0V617.376a32 32 0 0 1 11.2-24.32L752.192 260a32 32 0 0 1 41.6 48.64L416 632.064z" p-id="5412" data-spm-anchor-id="a313x.search_index.0.i13.4dfa3a81Mc8lKy"></path></svg>';
$defaults = array(
'class' => 'jb-blue radius-circle',
'text' => '随机文章',
'icon' => $random_icon,
'tooltip' => '随机阅读一篇文章',
'echo' => true
);
$args = wp_parse_args($args, $defaults);
$button = '<a href="' . esc_url(home_url('/wp-json/wp/v2/random-post')) . '" rel="external nofollow"
class="random-post-button but ' . esc_attr($args['class']) . ' ml10"
data-toggle="tooltip"
data-placement="bottom"
title="' . esc_attr($args['tooltip']) . '">'
. $args['icon']
. esc_html($args['text'])
. '</a>';
if ($args['echo']) {
echo $button;
}
return $button;
}
//使用api
/*https://你的域名/wp-json/wp/v2/random-post*/
/**
* 结束-注册自定义API端点用于随机文章跳转
*/
第二步我们打开自己网站根目录
zib-header.php 搜索
![图片[2]-子比美化-添加随机访问文章功能-九二分享](https://oss.xkzhi.cn/2025/06/28/xhyb1o.webp)
加入一下代码
/**
* 开始-注册自定义API端点用于随机文章跳转
*/
$random_button = zib_get_random_post_button(array(
'echo' => false
));
if ($random_button) {
$button .= $random_button;
}
/**
* 结束-注册自定义API端点用于随机文章跳转
*/
© 版权声明
© 版权声明 All Rights Reserved
THE END








暂无评论内容