add_rewrite_rule() not playing nice with child pages

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

1 Answer
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' );

Leave a Comment