Last active
January 29, 2019 08:09
-
-
Save orangerdev/c1ec794d9bcf66d02c8af901e74ca3cd to your computer and use it in GitHub Desktop.
Class to create basic controller on request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace YOUR_PLUGIN; | |
class Request | |
{ | |
private $url; | |
/** | |
* private variable | |
* make sure that the value of the properity is unique, lowercase, non whitespace and | |
* only accept alphabet and dash only | |
*/ | |
private $request_name = 'your-request'; | |
/** | |
* Construction | |
*/ | |
public function __construct() | |
{ | |
$this->url = home_url($this->request_name); | |
} | |
/* | |
* Register custom rules | |
* Hooked via filter generate_rewrite_rules, priority 999 | |
* @param Object $wp_rewrite | |
*/ | |
public function set_custom_rules($wp_rewrite) | |
{ | |
$wp_rewrite->rules[$this->request_name.'/([^/]+)/([^/]+)?$'] = 'index.php?'. $this->request_name .'=$matches[1]&action=$matches[2]'; | |
$wp_rewrite->rules[$this->request_name.'/([^/]+)/([^/]+)/([^/]+)?$'] = 'index.php?'. $this->request_name .'=$matches[1]&action=$matches[2]&value=$matches[3]'; | |
return $wp_rewrite; | |
} | |
/** | |
* Add custom query vars | |
* Hooked via filter query_vars, priority 999 | |
* @param array $vars [description] | |
*/ | |
public function add_query_vars($vars) | |
{ | |
$vars[] = $this->request_name; | |
$vars[] = 'action'; | |
$vars[] = 'value'; | |
return $vars; | |
} | |
/** | |
* Check endpoint request | |
* Hooked via action template_redirect, priority 999 | |
* @return void | |
*/ | |
public function check_request() | |
{ | |
global $wp_query; | |
if('' !== get_query_var($this->request_name) && '' !== get_query_var('action')) : | |
$controller = get_query_var($this->request_name); | |
$action = get_query_var('action'); | |
$value = get_query_var('value'); | |
$hook = $this->request_name.'/'.$controller.'/'.$action; | |
// do custom action | |
do_action($hook,$value); | |
endif; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can create custom controller with the link
https://your-website.example/your-request/posts/add without value in the end, or
https://your-website.example/your-request/posts/edit/1 with its value