0

I'm trying to change the output of pages depending on the URIs last section. This will be used to enable the user to change the page's presentation by changing the URL (e.g. /path/to/page/xml would show the page's content as XML).

The mode-selector should be ignored when Wordpress queries the page, so all three URIs should result in the same page content but add a query-parameter mode without doing a redirect (the parameter should be internal only, not visible to the user).

Example:

Unchanged Page: /path/to/page

Mode 1:         /path/to/page/mode1 => /path/to/page?mode=m1
Mode 2:         /path/to/page/mode2 => /path/to/page?mode=m2

When I add a rule to .htaccess, the parameter is added, but the page is not found (404). Wordpress seems to use the original URI, instead of the rewritten one.

I tried varients of the following rule, without success:

RewriteRule (.+)/mode1$ $1?mode=m1 [QSA]

What am I missing?

4
  • If you don't want the querystrings to be visible to the user, why don't you just use a PHP session instead? Or is there a reason I'm missing? With sessions you can also change the output of a page based on the value you're setting.
    – DeltaG
    Commented Dec 10, 2021 at 9:21
  • @DeltaG I want the user to be able to change the presentation of the page by changing the URL. Like .../page/booking for a booking-process or .../page/xml for an XML represendation of the page.
    – zoku
    Commented Dec 10, 2021 at 9:29
  • You should be able to do this using rewrite rules; check out the answer of this question: wordpress.stackexchange.com/questions/398461/…
    – Aboelabbas
    Commented Dec 10, 2021 at 13:55
  • @Aboelabbas Yes! This helped. I don't know what I did different than all the other times, but it works now. Thank you!
    – zoku
    Commented Dec 13, 2021 at 9:53

1 Answer 1

0

@Aboelabbas gave me the hint I needed. Although I don't really know what I did different, here is the working code for all three modes I need:

<?php
add_filter('query_vars', function ($query_vars) {
  $query_vars[] = 'mode';
  return $query_vars;
});

add_action('init', function () {
  add_rewrite_rule(
    '(.+)/buchung$', // Rule for URLs ending with "/buchung"
    'index.php?pagename=$matches[1]&mode=booking',
    'top'
  );

  add_rewrite_rule(
    '(.+/[^/]+)\.xml$', // Rule for URLs ending with "/anything.xml"
    'index.php?pagename=$matches[1]&mode=xml',
    'top'
  );

  add_rewrite_rule(
    '(.+/[^/]+)\.json$', // Rule for URLs ending with "/anything.json"
    'index.php?pagename=$matches[1]&mode=json',
    'top'
  );
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.