Skip to content

Instantly share code, notes, and snippets.

@orangerdev
Last active January 29, 2019 08:09
Show Gist options
  • Save orangerdev/c1ec794d9bcf66d02c8af901e74ca3cd to your computer and use it in GitHub Desktop.
Save orangerdev/c1ec794d9bcf66d02c8af901e74ca3cd to your computer and use it in GitHub Desktop.
Class to create basic controller on request
<?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;
}
}
@orangerdev
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment