0

I have been developing a language plugin for wordpress which works completely. The only thing that is missing now is the url-rewriting. I have been looking at a lot of websites, sources and other questions on stackoverflow, but I can't seem to get my permalinks to work.

I have been able to add a query string variable like so:

public function append_query_string($url) 
{
    $args = array('lang' => $this->get_locale());
    return add_query_arg($args, $url);
}
add_filter('page_link', array($this, 'append_query_string'));
add_filter('post_link', array($this, 'append_query_string'));
add_filter('the_permalink', array($this, 'append_query_string'));

This changes my links to http://www.mylink.com?lang=en_us for example. What I want now, is to add a permastruct so that user can have pretty url's (e.g. http://www.mylink.com/en/)

I have added the following piece of code:

public function add_query_var($vars)
{
    $vars['lang'] = $this->get_locale();
    return $vars;
}
add_filter('request' , array($this, 'add_query_var'), 10, 2 );

public function custom_permastruct() 
{
    add_permastruct('language', '%lang%', false);
}
add_action('wp_loaded', array($this, 'custom_permastruct'));

The only thing I need now is a rewrite rule, I presume, but I could be totally wrong. Anyone who knows what the best solution is for adding this permastruct?

-1

In your example

Change this:

public function custom_permastruct() 
{
    add_permastruct('language', '%lang%', false);
}

to this:

public function custom_permastruct() 
{
    add_rewrite_tag('%lang%','(lang)s','post_type=');
    add_permastruct('language', '%lang%', false);
}

Please note that this will only work on WordPress 3.4+

Other ways of doing it:

You need to create a new permalink and after to set some rewrite rules. The function add_permastruct is a good start. You can find a good example here: http://shibashake.com/wordpress-theme/wordpress-permalink-add and also here: https://code.tutsplus.com/articles/the-rewrite-api-post-types-taxonomies--wp-25488

That's a media library example, but you can use the same functionality for your language module.

  • Please, add code and explanation to the answer itself. Use external links only as reference. – cybmeta Jul 4 '17 at 11:51
  • That's an entire tutorial, I didn't want to copy-paste it here since I had the option to just add a link to it. I'm not related to that website. It was a good example and that's why I recommended it. – Rares P. Jul 4 '17 at 11:55
  • 2
    Just add the relevant parts. If the link is dead, the answer is useless. Thanks. – kaiser Jul 4 '17 at 12:08
  • That's a good point and a very strong argument. – Rares P. Jul 4 '17 at 12:08
  • I just edited my answer. Thanks for your feedback. – Rares P. Jul 4 '17 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.