Rewrite rule for open WordPress pages using slug or path

41 Views Asked by At

I've been working on a WordPress multilingual theme and I am trying to access my site pages using add_rewrite_rule function. This is a part of my code:

add_rewrite_rule( "^($language)/(.*)$", 'index.php?pagename=$matches[2]&language=$matches[1]', "top" );

Here I have a variable named $language which is a language code like "en". Then when I visit a page followed by "en" slug like https://example.com/en/blog works just fine, but it is only working for registered pages, not posts and other post types.

I can change pagename parameter to postname but then pages wont work. So I'm searching for a way to open a page or post using their slug, e.g:

add_rewrite_rule( "^($language)/(.*)$", 'index.php?path=$matches[2]...', "top" );

So when I visit https://example.com/en/blog it is like I'm visiting https://example.com/blog, whether blog is a page or post.

I found some other acceptable parameters for index.php like tagname, search, lang, etc. but none of them is what I'm looking for.

Note: I've already done the part that detects the language and changes the locale, contents and other things, I'm just looking for a way to display the contents.

This is also my own them so I have full access / right to edit the codes, so I am open for any other suggestions to do this. Thank you.

1

There are 1 best solutions below

0
Rashid On

You can try using name instead of pagename or postname to match any post type by its slug:

add_rewrite_rule( "^($language)/(.*)$", 'index.php?name=$matches[2]&language=$matches[1]', "top" );

and then you can parse your query something like:

function my_theme_parse_request($query) {
    if (isset($query['name']) && isset($query['language'])) {
        $name = $query['name'];
        $language = $query['language'];

        // Use $name and $language to retrieve and display content in the appropriate language
        // Example:
        $post = get_page_by_path($name, OBJECT, $post_type); // Check for both pages and posts
        if ($post) {
            // your post/page template
        }
    }
}
add_action('parse_query', 'my_theme_parse_request');