给网站添加随便看看小功能,原理是可以在网站博客发布的所有文章中,随机抽取一篇文章访问的效果。如下图:
操作方法:
1,找到自己的主题目录下functions.php文件,
2,将以下代码复制后加入到该文件中 ,
// 添加随便看看
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' );
//代码由大雄搜集站提供(soujiz.com)
3,具体使用
代码添加后,通过你网站的,域名 /?random 访问此链接看到效果。
例如本站: https://soujiz.com/?random,
如果你想要在导航菜单添加的话,在后台新建一个自定义 URL 菜单即可。输入该链接地址即可实现了。
© 版权声明
THE END
暂无评论内容