Wordpress - Using custom/dynamic "slug" for a page

Create a Page Template

Add a new page and give it the slug stores

Add A Public Query Variable

add_filter('query_vars', 'add_state_var', 0, 1);
function add_state_var($vars){
    $vars[] = 'state';
    return $vars;
}

Add a rewrite rule

This will direct your request to your stores page.

add_rewrite_rule('^stores/([^/]*)/?','index.php?post_type=page&name=stores&state=$matches[1]','top');

Within your Template

You can access your state variable as follows:

 $state = get_query_var('state');

Flush your Permalinks

Visit Settings->Permalinks to flush your permalinks and add your rewrite rule to the stack.


I found the answer on Wordpress' website and have tested the solution: https://codex.wordpress.org/Rewrite_API/add_rewrite_rule#Using_Custom_Templates_with_custom_querystring

Create a Page Template

Create a page template for stores and apply it to a page.

$stores = get_query_var('stores');

Add a Rewrite Tag

In your functions.php add a rewrite tag, which lets Wordpress know to look for the specific tag

function custom_rewrite_tag() {
  add_rewrite_tag('%stores%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

Add a Rewrite Rule

Now to format the URL and point it to the index.php with the vars, enter the following in your functions.php. Note: You have to update the page_id to the page_id of the stores page (it's 12 in this example).

  function custom_rewrite_rule() {
    add_rewrite_rule('^stores/([^/]*)/?','index.php?page_id=12&stores=$matches[1]','top');
  }
  add_action('init', 'custom_rewrite_rule', 10, 0);

From there you can browse to /stores/south-dakota/ and the $stores variable in your page template will be "south-dakota".


I was also trying to do the same and finally did it in following way.

Add the following code to your functions.php inside your theme.

add_filter('query_vars', 'add_state_var', 0, 1);
function add_state_var($vars){
    $vars[] = 'state';
    return $vars;
}

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

Inside you template, get the query variable using this

$state = get_query_var('state');