0

I'm lost in the world of Wordpress rewrites and I'm hoping someone can help...

I'm creating two custom members areas from my site; users logged in as certain roles will be able to view certain posts, guests won't be able to see the posts.

There are two areas for members, let's call them gold and silver

The gold/silver members 'dashboards' will be at http://example.com/gold or http://example.com/silver

I want to create a rewrite rule for blog posts so that if you go to http://example.com/gold/post-slug-here you see the post with a name of post-slug-here (without redirecting to http://example.com/post-slug-here). I need to keep the URL so I know which area the user is in (some posts will be viewable in both)

I've tried...

add_action( 'init', 'members_area_single_rewrites' );
function members_area_single_rewrites() {
    add_rewrite_rule(
    // The regex to match the incoming URL
    'gold/(.+?)/?$',
    // The resulting internal URL
    'index.php?pagename=$matches[1]',
    // Add the rule to the top of the rewrite list
    'top' );
}

I am resaving in Settings -> Permalinks after every code change.

Now if I visit the URL, it finds the post, but redirects to the non-prefixed URL. What am I missing?

I am also not sure if I can add 'gold' or 'silver' as an area query_var so that I can then do something like if (get_query_var('area') == 'gold') which would be super helpful.

  • Could you create gold and silver as taxonomies (tags, categories, custom) and prefix the URL in general with that? – kero Nov 26 '18 at 14:25
  • Don't flush_rewrite_rules() on init. Your rewrite rule probably isn't working and you're just experiencing the default behaviour. Either run the function once after activation or just manually flush them at Settings > Permalinks. – Jacob Peattie Nov 26 '18 at 14:34
  • @JacobPeattie - OK, I had been just saving Permalinks before I added that line so I don't think that's the issue, but I've removed it now. – Sarah Nov 26 '18 at 14:35
  • @kero Wouldn't the URL then have to be example.com/taxonomy-slug/gold/post-slug ? I could, but I don't really want to rely the admin to have to add every post to the correct taxonomy. At the moment they select whether it is a restricted post and which user roles should view it. – Sarah Nov 26 '18 at 14:38
  • @Sarah You can remove taxonomy-slug and only have /gold/post-slug or /silver/post-slug. How does the admin currently select restriction? Simply couple the taxonomy on that and nothing changes for the admin, the system can by default add these (with a bit of custom code) – kero Nov 26 '18 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.