In my default WordPress post type, I have a custom field that is named template, which can have a value of either blog or music.

I want to rewrite the permalink to be something like %music/my-song where my-song would be the name of the post.

I changed the permalink settings to custom structure /%template%/%postname%/.

I've added a post_link filter to update the template in the link:

add_filter('post_link', function($link, $post = null){

    if($post && ($template = get_field($template, $post->ID)))
        return str_replace('%template%', $template, $link);

    return $link;


I also added a rewrite tag for WordPress to detect the template:

add_rewrite_tag('%template%', '([^/]+', 'template=');

Once I save the permalinks, every thing seems to be working for my posts. However, when I try to access a page, it doesn't work.

For example, my contact page's permalink is /contact, and instead of displaying the contact page itself, it shows the home page.

  • Possible duplicate of How to create custom URL routes?
    – admcfajn
    Commented Aug 30, 2017 at 21:17
  • It's funny that it even works at all, you forgot to set the number of arguments to the filter (eg: add_filter('post_link', function, 10, 2) )
    – Tofandel
    Commented Nov 29, 2019 at 17:39


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.