Custom rewrite rules not working with WPML

Question

I have custom rewrite rules for posts on a WordPress website. The website is in french and I just added WPML to make it available also in english.
WPML is configured to use directories (/en) for english and base url for french.

I want to have a translation for my custom rules but I can’t make it works.

My current code is:

add_filter('generate_rewrite_rules', 'generateArticlesRewriteRules');
function generateArticlesRewriteRules($wp_rewrite)
{
  $rules = [];
  $terms = get_terms([
    'taxonomy' => 'post',
    'hide_empty' => false,
  ]);

  $post_type = 'post';

  foreach ($terms as $term)
    $rules['actualites/([^/]*)$'] = 'index.php?post_type='.$post_type.'&resources_post_type=$matches[1]&name=$matches[1]';

  // merge with global rules
  $wp_rewrite->rules = $rules + $wp_rewrite->rules;
}


add_filter('post_link', 'rewriteArticlesLinks', 1, 3);
function rewriteArticlesLinks($permalink, $post)
{
  $permalink = get_home_url().'/actualites/'.$post->post_name;
  return $permalink;
}

I’ve tried this but I get 404 errors or too many redirects.

function generateArticlesRewriteRules($wp_rewrite)
{
  // ...
  $rules['actualites/([^/]*)$'] = 'index.php?post_type='.$post_type.'&resources_post_type=$matches[1]&name=$matches[1]';
  $rules['news/([^/]*)$'] = 'index.php?post_type='.$post_type.'&resources_post_type=$matches[1]&name=$matches[1]';
  // ...
}

function rewriteArticlesLinks($permalink, $post)
{
  if (ICL_LANGUAGE_CODE == 'en')
    $permalink = get_home_url().'/en/news/'.$post->post_name;
  else
    $permalink = get_home_url().'/actualites/'.$post->post_name;

  return $permalink;
}

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/custom-rewrite-rules-not-working-with-wpml/">

Custom rewrite rules not working with WPML</a>
0
, , , , fdehanne 4 months 0 Answers 41 views 0

Leave an answer