WP URL Rewrite Sample
<?php | |
class Request { | |
public static $pagename = null; | |
public static $module = null; | |
public static $action_page = null; | |
public static $action_id = null; | |
public static $app_slug = null; | |
public function __construct() { | |
add_action( 'init', [ $this, 'setup_rewrite_rule' ] ); | |
add_action( 'parse_request', [ $this, 'app_parse_request' ] ); | |
add_action( 'template_redirect', [ $this, 'redirect_page' ] ); | |
} | |
public function setup_rewrite_rule() { | |
add_rewrite_tag( '%module%', '([A-Za-z0-9\-\_]+)' ); | |
add_rewrite_tag( '%action_page%', '([A-Za-z0-9\-\_]+)' ); | |
add_rewrite_tag( '%action_id%', '([A-Za-z0-9\-\_]+)' ); | |
$app_page = get_option( 'options_app_page', '' ); | |
if( $app_page != '' ) { | |
$_post = get_post( $app_page ); | |
$_app_slug = $_post->post_name; | |
self::$app_slug = $_app_slug; | |
add_rewrite_rule( '^'.$_app_slug.'/([A-Za-z0-9\-\_]+)$','index.php?pagename='.$_app_slug.'&module=$matches[1]', 'top' ); | |
add_rewrite_rule( '^'.$_app_slug.'/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)$','index.php?pagename='.$_app_slug.'&module=$matches[1]&action_page=$matches[2]', 'top' ); | |
add_rewrite_rule( '^'.$_app_slug.'/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)$','index.php?pagename='.$_app_slug.'&module=$matches[1]&action_page=$matches[2]&action_id=$matches[3]', 'top' ); | |
} | |
} | |
public function app_parse_request( $query ) { | |
$qv = $query->query_vars; | |
if( isset( $qv['pagename'] ) && $qv['pagename'] != '' ) { | |
self::$pagename = $qv['pagename']; | |
} | |
if( isset( $qv['module'] ) && $qv['module'] != '' ) { | |
self::$module = $qv['module']; | |
} | |
if( isset( $qv['action_page'] ) && $qv['action_page'] != '' ) { | |
self::$action_page = $qv['action_page']; | |
} | |
if( isset( $qv['action_id'] ) && $qv['action_id'] != '' ) { | |
self::$action_id = $qv['action_id']; | |
} | |
} | |
public function redirect_page() { | |
if( self::$app_slug == self::$pagename && self::$module == '' ) { | |
wp_redirect( home_url( '/' ) ); | |
exit; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment