0
\$\begingroup\$

Please look at this working WordPress code:

add_action('init', 'add_custom_rewrites');
function add_custom_rewrites(){
  add_rewrite_rule(
    '^(en|fr|es|de)/inspiration/testimonial/([^/]*)?',
    'index.php?post_type=testimonial&lang=$matches[1]&name=$matches[2]',
    'top'
  );

  add_rewrite_rule(
    '^inspiration/testimonial/([^/]*)?',
    'index.php?post_type=testimonial&lang=it&name=$matches[1]',
    'top'
  );
}

The first rule matches a post under an url like this:

example.com/en/inspiration/testimonial/test-post

The second matches this:

example.com/inspiration/testimonial/test-post

Which is for the default language (it). Since the default lang is implicit, it's not written in the url, but under the hood it's like example.com/it/inspiration/testimonial/test-post.

Well, the question: is there any better way of achieving this result? Particularly, is there any way of doing it with only one single rule?

\$\endgroup\$
  • \$\begingroup\$ Only for the fun (don't use this absolutly not flexible stupid thing), you can do it in a single replacement with ^(?|(en|es|fr|de)()/inspiration|(i)nspira(t)ion)/testimonial/([^/]*) and index.php?post_type=testimonial&lang=$matches[1]$matches[2]&name=$matches[3]. \$\endgroup\$ – Casimir et Hippolyte Jul 1 at 15:16
  • \$\begingroup\$ Does defaulting to Italian have to be hard-coded in the URL-rewriting rules? What language appears if you go to index.php?post_type=testimonial&lang=&name=something? (Are you using a plugin like Polylang or Multisite Language Switcher?) \$\endgroup\$ – 200_success Jul 1 at 20:21
  • \$\begingroup\$ @CasimiretHippolyte kindly avoid sabotaging the site design. Please post a review instead of a comment. \$\endgroup\$ – mickmackusa Jul 1 at 22:27
  • \$\begingroup\$ @200_success hi, I don't need to hardcode IT in url, I can omit, and it will show italian. Currently using polylang pro, but I don't think it's related to the issue. \$\endgroup\$ – Luca Reghellin Jul 2 at 16:11

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.