为wordpress添加随便看看
2017-11-28 本文已影响0人
老铁缺铁
随便看看其实就是随机阅读,点一下就会随机打开一篇文章。
记得刚接触wordpress那会还添加过这个功能,后来换了主题也懒得折腾了也就没有在添加这个功能。
wordpress用的人很多有很多大牛,一些想要的功能很多都可以通过安装插件来实现,但是很多人还是喜欢直接用代码来实现。
wordpress添加随便看看可以通过将下面的代码添加到wordpress当前主题的functions.php文件中来实现
1.把下面的代码添加到wordpress当前主题的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' );
2.通过http://xxxx/?random 来访问,xxx替换成你的域名就可以了