-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirect-processor.php
66 lines (54 loc) · 1.36 KB
/
redirect-processor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
class WpRandomRedirectProcessor {
public $redirectOptions;
public function __construct() {
$this->redirectOptions = get_option( 'wp_random_redirect_option_name' );
add_action( 'template_redirect', [ $this, 'template_redirect' ] );
}
public function template_redirect() {
$path = $this->getCurrentUrlPath();
$randomPath = $this->getRandomUrlPath();
if ( $path != '' && $path == $randomPath ) {
wp_redirect(
$this->getRandomPostUrl() .
$this->getSuffix()
);
die;
}
}
public function getCurrentUrlPath() {
return $this->clearPath(
WpRandomRedirectHelper::getRequest()
);
}
public function clearPath( $path ) {
return trim( $path, '/' );
}
public function getRandomUrlPath() {
if ( isset( $this->redirectOptions['url_path'] ) ) {
return $this->clearPath( $this->redirectOptions['url_path'] );
}
return '';
}
public function getRandomPostUrl() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1,
);
$the_query = new WP_Query( $args );
$url = get_home_url();
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$url = get_permalink();
}
wp_reset_postdata();
}
return $url;
}
public function getSuffix() {
return $this->redirectOptions['url_suffix'];
}
}
new WpRandomRedirectProcessor;