WordPress使用代码给你的博客添加一个随机看看的功能
随便看看
随机给出文章看看,就是本博客菜单栏上的随便看看的功能。随机在博客中抽取一篇文章来访问,
开始食用
将以下代码加入到主题目录中的“functions.php”文件的 ?> 之前即可
注意的是:本模板的是在functions-theme.php 有些模板会不一样,所以自行致知
以下为代码
- 将以下代码加入到主题目录中的“functions.php”文件的 ?> 之前即可。
// 添加随便看看
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' );
// 随便看看结束
完结
访问你网站的域名/?random
即可看到效果
如:https://www.ly522.com/?random
还有一种就是创建一个PHP文件讲代码放进去,访问即可
更多好玩功能请持续关注记磊博客哦
推荐:https://www.ly522.com/750.html
© 版权声明
THE END
暂无评论内容