random-redirect.php
| 1 | <?php |
| 2 | /* |
| 3 | Plugin Name: Random Redirect |
| 4 | Plugin URI: http://wordpress.org/extend/plugins/random-redirect/ |
| 5 | Description: Allows you to create a link to yourblog.example.com/?random which will redirect someone to a random post on your blog, in a StumbleUpon-like fashion. |
| 6 | Version: 1.2-wpcom |
| 7 | Author: Matt Mullenweg |
| 8 | Author URI: http://photomatt.net/ |
| 9 | */ |
| 10 | |
| 11 | function matt_random_redirect() { |
| 12 | // Acceptables URL formats: /[...]/?random=[post type], /?random, /&random, /&random=1 |
| 13 | if ( ! isset( $_GET['random'] ) && ! in_array( strtolower( $_SERVER['REQUEST_URI'] ), array( '/&random', '/&random=1' ) ) ) |
| 14 | return; |
| 15 | |
| 16 | // Ignore requests that include more than just the random parameter. |
| 17 | if ( ! empty( $_POST ) || ( isset( $_GET['random'] ) && count( $_GET ) > 1 ) ) |
| 18 | return; |
| 19 | |
| 20 | // Persistent AppEngine abuse. ORDER BY RAND is expensive. |
| 21 | if ( strstr( $_SERVER['HTTP_USER_AGENT'], 'AppEngine-Google' ) ) |
| 22 | wp_die( 'Please <a href="http://en.support.wordpress.com/contact/">contact support</a>' ); |
| 23 | |
| 24 | // Use the post type of the current page as the context for the random lookup. |
| 25 | $post_type = get_post_type(); |
| 26 | |
| 27 | // /?random should always show a random post, even if the home page is a static page. |
| 28 | if ( '/' == $_SERVER['DOCUMENT_URI'] ) |
| 29 | $post_type = 'post'; |
| 30 | else |
| 31 | $post_type = get_post_type(); |
| 32 | |
| 33 | if ( ! $post_type ) |
| 34 | $post_type = 'post'; |
| 35 | |
| 36 | global $wpdb; |
| 37 | $random_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = %s AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1", $post_type ) ); |
| 38 | $permalink = get_permalink( $random_id ); |
| 39 | wp_safe_redirect( $permalink ); |
| 40 | exit; |
| 41 | } |
| 42 | |
| 43 | add_action( 'template_redirect', 'matt_random_redirect' ); |
| 44 |