Search code examples
wordpressurl-rewritingadditionrules

Change post URL with WordPress add_rewrite_rule()


I had a post with URL like this:

http://example.com/news/postname

the 'Custom Structure' setting in wp-admin is like this:

http://example.com[/news/%postname%]

I'd like to change the URL of post-name start with my post(e.g. mypost-postname) to

http://example.com/my-news/postname

I try use add_rewrite_rule like this:

add_action( 'init', 'new_posts_with_new_url' );
function new_posts_with_new_url()
{
    add_rewrite_rule('my-news/([^/]*)/?','index.php?pagename=news/mypost-$matches[1]','top');
}

But it seems not to work.

Which step did I do wrong? Many thanks.


Solution

  • Wrong in index.php?pagename=news/mypost-$matches[1] in my case,

    you can use echo add_query_arg( $wp->query_vars, home_url() ); to see the real url.