add_rewrite_rule( string $regex, string|array $query, string $after = 'bottom' )

Adds a rewrite rule that transforms a URL structure to a set of query vars.


Description Description

Any value in the $after parameter that isn’t ‘bottom’ will result in the rule being placed at the top of the rewrite rules.


Parameters Parameters

$regex

(string) (Required) Regular expression to match request against.

$query

(string|array) (Required) The corresponding query vars for this rewrite rule.

$after

(string) (Optional) Priority of the new rule. Accepts 'top' or 'bottom'.

Default value: 'bottom'


Top ↑

Source Source

File: wp-includes/rewrite.php

function add_rewrite_rule( $regex, $query, $after = 'bottom' ) {
	global $wp_rewrite;

	$wp_rewrite->add_rule( $regex, $query, $after );
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Array support was added to the $query parameter.
2.1.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Samuel Elh

    A quick example: processing rules to make a subscribers page, hoping it helps.

    add_action('init', function() {
    
    	$page_id = 2; // update 2 (sample page) to your custom page ID where you can get the subscriber(s) data later
    	$page_data = get_post( $page_id );
    
    	if( ! is_object($page_data) ) { // post not there
    		return;
    	}
    
    	add_rewrite_rule(
    		$page_data->post_name . '/subscriber/([^/]+)/?$',
    		'index.php?pagename=' . $page_data->post_name . '&my_subscribers=1&my_subscriber=$matches[1]',
    		'top'
    	);
    
    });
    

    Now in your page template ( if you have one, or while filtering this custom page’s content ), you can get the displayed subscriber slug by calling get_query_var('my_subscriber'), but first, pass 'my_subscriber' to the query variables:

    add_filter('query_vars', function($vars) {
        $vars[] = "my_subscriber";
        return $vars;
    });
    

You must log in before being able to contribute a note or feedback.