WordPress添加「隨便看看」功能,就是隨機給出文章閱讀。點擊一下隨機給您一篇網站裏面的文章閱讀,功能將直接使用WordPress的Functions函數實現。
首先將如下代碼添加到主題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即可隨機進入一篇文章閱讀。URL根據個人需求,無論放在哪裏,只要有人點擊,就可以隨機閱讀文章。
未經允許不得轉載:格林尼治源碼 » WordPress純代碼添加「隨便看看」功能隨機閱讀文章