博客增加随便看看功能

分享
401 1

 

介绍

点击后会随机展示博客内的一篇文章,就像本博客菜单栏上的随便看看的功能。

 

使用

将以下代码加入到主题目录中的“functions.php”文件中即可

[reply]

// 添加随便看看
function random_postlite() {
global $wpdb;
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
if ( isset( $_GET['random_cat_id'] ) ) {
$random_cat_id = (int) $_GET['random_cat_id'];
$query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = $random_cat_id) INNER JOIN $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
}
if ( isset( $_GET['random_post_type'] ) ) {
$post_type = preg_replace( '|[^a-z]|i', '', $_GET['random_post_type'] );
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
}
$random_id = $wpdb->get_var( $query );
wp_redirect( get_permalink( $random_id ) );
exit;
}
if ( isset( $_GET['random'] ) )
add_action( 'template_redirect', 'random_postlite' );

// 随便看看结束

[/reply]

 

测试

访问你网站的域名/?random      即可看到效果

如:https://www.blogman.cn/?random

 

最后更新 2024-03-06
那年今日
09月
15日
  • 🔸暂无数据

评论 ( 1 )
悄悄话
  1. 酷酷的我 Lv1⭐️

    看看

    2023-09-15新疆电信 回复