-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddVirtualPage.class.php
More file actions
93 lines (72 loc) · 1.97 KB
/
Copy pathAddVirtualPage.class.php
File metadata and controls
93 lines (72 loc) · 1.97 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Helper class for creating a virtual
* page in WordPress. This can be changed
* to further add parameters to the custom
* page. For now it is only creating a simple
* custom URL like domain.com/custom-url-slug/
*
* i.e, new AddVirtualPage('custom-url-slug', $template_path);
*
* Once this is called don't forget to clear your
* permalink cache for the new virtual page to work
*
* @category WordPress
* @package AddVirtualPage
* @author Ahmad Karim <ahmu83@gmail.com>
* @license https://opensource.org/licenses/GPL-2.0 GPL-2.0+
* @link https://www.ahmadkarim.com/
*/
class AddVirtualPage {
private $slug;
private $template_path;
/**
* Add virtual page
*
* @param string $slug
* @param string $template_path
*/
function __construct($slug, $template_path) {
$this->slug = $slug;
$this->template_path = $template_path;
add_filter('generate_rewrite_rules', array($this, 'generate_rewrite_rules'));
add_filter('query_vars', array($this, 'query_vars'));
add_action('template_redirect', array($this, 'template_redirect'));
}
/**
* Callback for the generate_rewrite_rules filter hook
*
* @param object $wp_rewrite [description]
* @return void
*/
public function generate_rewrite_rules($wp_rewrite) {
$slug = $this->slug;
$wp_rewrite->rules = array_merge(
array("{$slug}/?$" => "index.php?{$slug}=1"),
$wp_rewrite->rules
);
}
/**
* Callback for the query_vars filter hook
*
* @param array $query_vars
* @return array
*/
public function query_vars($query_vars) {
$query_vars[] = $this->slug;
return $query_vars;
}
/**
* Callback for the template_redirect action hook
*
* @return void
*/
public function template_redirect() {
$slug = intval(get_query_var($this->slug));
$template_path = $this->template_path;
if ( $slug && file_exists($template_path) ) {
include $template_path;
die;
}
}
}