add_rewrite_rule() not playing nice with child pages

The question:

function my_add_rewrite_rules() {

  add_rewrite_rule('testing/([^/]+)?$', 'index.php?pagename=testing&event_slug=$matches[1]', 'top' ); 

add_action( 'init', 'my_add_rewrite_rules' );

function add_query_vars( $query_vars ) {
  $query_vars[] = 'event_slug';
  return $query_vars;
add_filter( 'query_vars', 'add_query_vars' );   

/testing/foo – Works, shows foo

If I have testing set to no parent, the rewrite works and everything is good to go.

If I set testing to a child of, lets say about, and update the add_rewrite_rule to..

add_rewrite_rule('about/testing/([^/]+)?$', 'index.php?pagename=testing&event_slug=$matches[1]', 'top' ); 

… it loads about/testing but strips out my custom query_var and displays the page normally.

/about/testing/foo – Loads page, doesn’t show foo

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

if it’s a child page, you have to update pagename to reflect the parent/child path:

add_rewrite_rule('about/testing/([^/]+)?$', 'index.php?pagename=about/testing&event_slug=$matches[1]', 'top' );

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment