This works (Wordpress redirects to the canonical URL of the post with the given slug):

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

This is not working (404)

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

Why? :)

  • if the first one redirects, it's actually not working, you're getting a 404 and WordPress is guessing what page you mean to be loading and redirecting you there. is the desired page a child of another page? what happens if you hardcode a page_id value in your rule instead?
    – Milo
    Commented Jun 19, 2014 at 17:14
  • With harcoded page_id or pagename it always works; with $matches[1] works but only with pages (maybe because WP is guessing? No idea), it doesn't work with the Custom Post type I'm trying to use.
    – flip79
    Commented Jun 20, 2014 at 8:59
  • THIS seems to work! wordpress.stackexchange.com/a/53742/33385
    – flip79
    Commented Jun 20, 2014 at 9:09
  • pagename is the query var for the page post type, for custom post types the query var is the slug you registered the post type under. Have a look at WP_Query in codex for valid query vars you can set.
    – Milo
    Commented Jun 20, 2014 at 16:02


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.