| 1 |
<?php |
| 2 |
|
| 3 |
require_once __DIR__ . '/url.php'; |
| 4 |
|
| 5 |
/** |
| 6 |
* URL action - redirect to a URL |
| 7 |
*/ |
| 8 |
class Random_Action extends Url_Action { |
| 9 |
/** |
| 10 |
* Get a random URL |
| 11 |
* |
| 12 |
* @return string|null |
| 13 |
*/ |
| 14 |
private function get_random_url() { |
| 15 |
// Pick a random WordPress page |
| 16 |
global $wpdb; |
| 17 |
|
| 18 |
$id = $wpdb->get_var( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_status='publish' AND post_password='' AND post_type='post' ORDER BY RAND() LIMIT 0,1" ); |
| 19 |
if ( $id ) { |
| 20 |
$url = get_permalink( $id ); |
| 21 |
|
| 22 |
if ( $url ) { |
| 23 |
return $url; |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
return null; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Run this action. May not return from this function. |
| 32 |
* |
| 33 |
* @return void |
| 34 |
*/ |
| 35 |
public function run() { |
| 36 |
$target = $this->get_random_url(); |
| 37 |
|
| 38 |
if ( $target ) { |
| 39 |
$this->redirect_to( $target ); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
public function needs_target() { |
| 44 |
return false; |
| 45 |
} |
| 46 |
|
| 47 |
public function name() { |
| 48 |
return __( 'Redirect to random post', 'redirection' ); |
| 49 |
} |
| 50 |
} |
| 51 |
|