0

I have made my own routes by using add_rewrite_rule method. I would like to know if it is possible using given method to force all my created routes to redirect to URL where there is trailing slash in the end. For example if i do

add_rewrite_rule('^my-route/', 'index.php?_my_route=1', 'top')

or

add_rewrite_rule('^my-route', 'index.php?_my_route=1', 'top')

and i make a call to http://site.dev/my-route then it does not redirect it to http://site.dev/my-route/. If it is possible then i would be thankful for sharing :).

-1

If think this will work for you Add this is functions.php

add_action( 'init',function(){
  global $wp;
  $current_url = home_url(add_query_arg(array(),$wp->request));
  $last_char = substr($current_url, -1); 

 if($last_char == '/' && filter_var($current_url, FILTER_VALIDATE_URL)){
   wp_redirect( trailingslashit( $current_url ) );
 }
});
  • We can use others, if using only that method is not enough for redirection. Maybe other way is the only correct way, so ideas are welcomed! :) – Marttin Notta Nov 2 '16 at 14:34
  • @MarttinNotta Just to confirm you want to redirect the current url to url with slash at end if there is no slash? right? – blackstar Nov 2 '16 at 14:36
  • Yes, this is what i want, but i would like it the way wordpress does it with its pages, if you have page names cartoons and you hit the page without no trailing slash then wordpress will make the redirect (no .htacces because im using nginx) – Marttin Notta Nov 2 '16 at 14:38
  • @MarttinNotta I updated answer check if it works and if you are not happy than you can comment – blackstar Nov 2 '16 at 14:44
  • This redirect works indeed, but unfortunately i have to manually check it which is not what i entirely want... i managed to get my code working using only add_rewrite_rule but i have not fully understood why it does so. By the way i did not give you -1... – Marttin Notta Nov 2 '16 at 15:03

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.