本教程将详细介绍如何编写代码实现随机文章跳转功能,让用户能够轻松地在你的网站上随机浏览不同的文章内容。通过本教程,你将学习到如何使用Web技术来构建这一功能,从而为用户提供一种新颖、有趣的浏览体验。无论你是个人博客作者、网站开发者还是内容创作者,本教程都将为你提供实用的指导和灵感。
简介
- 这个功能适合随机预览文章的功能,点击一次更换一次文章。
- 将以下 PHP 代码加入到主题目录中的
/www/wwwroot/huliku.com/wp-content/themes/zibll/functions.php
文件的即可。 - 添加完成之后访问:
你网站的域名/?random
即可看到效果。
代码部署
/*添加随便看看 @url:huliku.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' );
Comments NOTHING