Using Wordpress add_rewrite_rule with Polylang plugin

367 Views Asked by At

I am using this code to add rewrite_rule for Wordpress to create Child posts For another post type

add_action( 'init', function() {add_rewrite_rule( '^property/(.*)/units/([^/]+)/?$','index.php?property_units=$matches[2]','top' );});

add_filter( 'post_type_link', function( $link, $post ) {
  if ( 'property_units' == get_post_type( $post ) ) {
    if( $post->post_parent ) {
      $parent = get_post( $post->post_parent );
      if( !empty($parent->post_name) ) {return str_replace( '%property_name%', $parent->post_name, $link );}
    }
  }
  return $link;
}, 10, 2 );

And it works well

But when i add Polylang plugin, it only works with the default language and does not work for other languages

2

There are 2 best solutions below

0
On

My PolyLang settings was set to use language from directory name, hide default language and remove /language in permalink.

I use this code for custom URI/URL that runs independent (not based on post or page) and it can work with URLs /custompage, /en/custompage.

add_rewrite_rule('^([a-zA-Z]{0,2}/?)custompage/?$', 'index.php?lang=$matches[1]&custompage=index', 'top');
add_rewrite_rule('^([a-zA-Z]{0,2}/?)custompage/my?$', 'index.php?lang=$matches[1]&custompage=my-custompage', 'top');

add_rewrite_tag('%custompage%', '([^&]+)');

For custom URL/URL based on post or page.
I've created page with certain slug (custompage) and translated into languages with PolyLang. I use the code below. The postIds is all post IDs that are translated for certain page.
Example หน้ากำหนดเอง is in Thai and ID 166, custompage is in English and ID 167. The IDs will be array(166, 167).

foreach ($postIds as $postId) {
    $Post = get_post($postId);
    if (!is_object($Post)) {
        continue;
    }

    add_rewrite_rule('^([a-zA-Z]{0,2}/?)' . $Post->post_name . '/my/?$', 'index.php?lang=$matches[1]&pagename=' . $Post->post_name . '&custompage=my-custompage', 'top');
    unset($Post);
}// endforeach;

add_rewrite_tag('%custompage%', '([^&]+)');

I have to add rules for all of the post's translations at once, otherwise it won't work.

Don't forget to save permalink in WordPress settings page to flush the rewrite rules before test.

0
On
add_rewrite_rule( '^property/(.*)/units/([^/]+)/?$','index.php?property_units=$matches[2]','top' )

need to add ?lang=en to the url