CoreNext主题美化 - 文章底部添加随机文章功能
为了提升博客的趣味性,让用户在浏览的时候不那么枯燥,我们可以添加一个随机文章功能,让用户可以体验随机阅读的乐趣,好软猫给大家带来了自用的教程。
效果演示
详细教程
在网站后台
-外观
-主题编辑器
-子主题
-functions.php
插入以下代码
<!--随机文章_好软猫[www.haoruanmao.com]-->
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' );
在需要随机文章的地方加入:https://域名/?random
即可随机访问文章
本站文末样式
好软猫温馨提示您
本文最后更新于
文章没读爽?点我试试随机文章
2024-01-6
,部分内容具有时效性,如有失效,请评论留言阅读至此,本文已完结
THE END