add_rewrite_rule with trailing slash redirects

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 :).

Topic rewrite-rules Wordpress

Category Web


just change your rule to this

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

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 ) );
 }
});

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.