Wordpress Web Application Development(Third Edition)
上QQ阅读APP看书,第一时间看更新

Creating the routing rules

There are various ways and action hooks used to create custom rewrite rules. We will choose the init action to define our custom routes for the user section, as shown in the following code:

    public function manage_user_routes() { 
add_rewrite_rule( '^user/([^/]+)/?',
'index.php?control_action=$matches[1]', 'top' );
}

We can call this function through the init action. Let's add the action call the constructor of the WPWAF_Config_Manager class, as shown in the following code:

    class WPWAF_Config_Manager{ 
public function __construct(){
add_action( 'init', array( $this, 'manage_user_routes' ) );
}
}

Based on the discussed requirements, all the URLs for the user section will follow the /user/custom action pattern. Therefore, we will define the regular expression for matching all the routes in the user section. Redirection is made to the index.php file with a query variable called control_action. This variable will contain the URL segment after the /user segment. The third parameter of the add_rewrite_rule function will decide whether to check this rewrite rule before the existing rules or after them. The value of top will give a higher precedence, while the value of bottom will give a lower precedence.

We need to complete two other tasks to get these rewriting rules to take effect:

  • Add query variables to the WordPress query_vars
  • Flush the rewriting rules