Using WP Rewrite, but just not “getting it”

I’m trying to use WP Rewrite to avoid having to enter anything into an htaccess file. So far, I have this one working just fine (it loads a post from a Custom Post Type):

$leader_structure = 'performance/leaders/%leader%';
$wp_rewrite->add_rewrite_tag("%leader%", '([^/]+)', "leader=");
$wp_rewrite->add_permastruct('leader', $leader_structure, false);

Basically, if you go to http://domain.com/performance/leaders/some-slug-here, it’ll properly load the content from http://domain.com?leader=some-slug-here.

Read More

However, when I try it again with a non-custom-post-type (just normal WP posts), I can’t get it to work. Here’s what I’m doing:

$scenarios_structure = 'our-thinking/scenarios/%post%';
$wp_rewrite->add_rewrite_tag("%post%", '([^/]+)', "name=");
$wp_rewrite->add_permastruct('scenarios', $scenarios_structure, false);

So here, I want it so that http://domain.com/our-thinking/scenarios/some-post-slug should load the single WP post. But it doesn’t. When I go to that URL, it redirects to http://domain.com/some-post-slug.

It’s probably plainly obvious what I’m doing wrong to someone else, but I’m just not getting it. My WordPress permalink settings are set to “Post name”. And my .htaccess file is untouched.

Related posts

1 comment

  1. Your rewrite setting is good, but WordPress are redirect to the canonical url of the post. This is done by WodPress to prevent bad indexing for duplicate content (when an identical content is accessible via 2 different urls).

    You can prevent that removing the canonical redirect filter:

    add_action('wp_loaded', function() {
      remove_filter('template_redirect', 'redirect_canonical');
    });
    

    However this is not a recommned way, in fact, if you do it your post will be accessible both via the regular url and the new created url.

    When you want to change the default post permastruct, the recommend way is to adjust the permalink structure in WordPress permalink settings, so in your case the permalink structure shoul be

    our-thinking/scenarios/%postname%
    

    and to prevent it affects any other custom post type or custom taxonomy, when you register them, use the argument $rewrite with the key 'with_front' set to false, e.g. :

    ...
    'rewrite' => array( 'with_front' => false )
    ...
    

Comments are closed.