Sunday, April 17, 2016

Add dynamic prefix in WordPress page url

Leave a Comment

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 Answers

Answers 1

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; } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment