Rewriting every url

I have a question regarding permalinks and rewriting url’s. I am writing a translation plugin and I would like to add the language shortcode in my url (Something like http://eyewebz.com/EN/other_permalinks). Currently I am assigning a $_Session-variable to hold the current selected language, but this isn’t really visible for the users.

I am able to rewrite the url with the below code, but after altering the url, the page doesn’t show any content and the global $post-variable is completely empty. Code is below.

function alter_link_language($permalink)
{
    $active_language = get_user_selected_language();
    $current_language_shortcode = strtoupper( $active_language["shortname"] );

    $permalink = str_replace(get_bloginfo('home'), '', $permalink);
    return get_bloginfo('home') . "https://wordpress.stackexchange.com/" . $current_language_shortcode . $permalink;
}
add_filter('post_link', 'alter_link_language', 10);
add_filter('page_link', 'alter_link_language', 10);

If anyone could help me on wy way with this one, it would be greatly appreciated!

thanks in advance!

1
1

There’s not a good way to prepend a permalink with a URI base that I know of and keep WordPress happy at the same time. You can however add the language to the end of the URI with add_rewrite_endpoint();

add_action('init', 'foobar_rewrite_tag');
function foobar_rewrite_tag(){
     $languages = array('en', 'sp'); // Probably have this sourced from your plugin options
     foreach($languages as $language)
         add_rewrite_endpoint( $language, EP_PERMALINK | EP_PAGES);
}

You could use a simple getter function like this in your templates:

function get_language_code(){
    global $wp_query;
    $languages = array('en', 'sp'); //Source this from your plugin options
    foreach($languages as $language)
        if(isset($wp_query->query_vars[$language])) //Note this will not have a value assigned, so we check if it's set to determine the language
             return $language;
}

Your permalinks would look like the following:

  1. http://domain.com/page-name/en
  2. http://domain.com/page-name/sp

I know it’s not exactly as you desire, but it’s the easiest way to wrangle WordPress for this type of approach.

Reference: http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint

Leave a Comment