3
votes

I need to add dynamic prefix in page url.

You can help with how can I achieve this with Rewrite_API

Problem

In my WordPress website, I've few pages which I want to access using prefix before the page name in URL. For example, normally page is accessible using

http://example.com/page-name

I want to add dynamic prefix(location) before the page name. So I want to access the page like below

http://example.com/country/state/page-name

What I tried so far:

I tried to use below filter to add rewrite tag just before the page name in url.

add_action( 'init', array( $this, 'custom_rewrite_rules' ), 1, 0 ); 
 /*
* Rewrite page urls
* adding prefix to page urls
* @doc: http://stackoverflow.com/questions/17613789/wordpress-rewrite-add-base-prefix-to-pages-only
*/
function custom_rewrite_rules()
{
    global $wp_rewrite;
    // add rewrite tag for location
    $wp_rewrite->add_rewrite_tag( "%region%", '([^/]+)', 'region=' );

    $wp_rewrite->page_structure = $wp_rewrite->root . '%region%/%pagename%';        


}// end func

Above action hook allows me to have dynamic page url in frontend and in backend. For example, I can see page urls are now

http://example.com/%region%/page-name

What I need

As I have dynamic url's generated now, I want to replace %region% part of the url with the location string I want, It could be just country name or country/state name combination.

Thanks in Advance.

1
Did you manage to resolve this? I am trying to solve pretty much the same thing. - RobM
Not yet, I've tried @user5200704 answer, but I stuck with the problem. I just need to change url's in the frontend, in backend url shoud be with %region% rewrite tag. Also it should load the same page doesn't matter what the prefix is. currently all the solution I tried gives me 404 error. - aakash

1 Answers

1
votes

Change page link using wordpress filter

add_filter( '_get_page_link', 'custom_region_page_link', 10, 2 );

function custom_region_page_link( $link, $post_id ){
    //$slug = get_post_meta( $post_id, 'key', true );
    $link = str_replace('%region%', 'india', $link);
    return $link;
}