FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Adding a Trailing "/" to WordPress Permalinks

Problem: You use a custom permalink structure that doesn't end in a /, which causes ALL permalinks (pages, categories, etc) to NOT have an ending /.

Solution: Either hook into the user_trailingslashit filter, or use htaccess RedirectMatch

Let's say that like AskApache your permalink structure is something that doesn't end in a '/' like:

/%category%/%postname%.html

The WP_Rewrite class has a var named $use_trailing_slashes that is set dynamically based upon whether or not your custom permalink structure ends in a '/'.

$this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );

This means that all WP generated links (the_permalink, category_link, the_permalink_rss, etc.) will not end in a '/'. So for category pages WP will show '/category/category' instead of '/category/category/'.

Sample user_trailingslashit Filter

The user_trailingslashit function applies the 'user_trailingslashit' filter to the result prior to returning it. It provides the url and the type of url to the filter.

$string = apply_filters('user_trailingslashit', $string, $type_of_url);

So to hook into this and add a trailing slash to all urls other than single posts add this code to a plugin file or your functions.php theme file.

function fix_trailingsss($s='',$t='single')
{
  if($t!='single')$s=rtrim($s,'/').'/';
  return preg_replace('/^(.*)([^l/])$/i', '\1\2/',$s);
}
add_filter('user_trailingslashit', 'fix_trailingsss', 9999,2);

Htaccess RedirectMatch

You can setup an .htaccess redirect to force category urls to always use a trailing slash like this:

RedirectMatch 301 ^/category/([^/]+)$ /category/$1/

WordPress permalink PHP RedirectMatch wordpress

 

 

Comments