FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home » WordPress » Adding a Trailing "/" to WordPress Permalinks

by 1 comment

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

Custom Permalinks

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/

Tags

Comments Welcome

Information is freedom. Freedom is non-negotiable. So please feel free to modify, copy, republish, sell, or use anything on this site in any way at any time ;)

My Online Tools

Popular Articles
Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two.
-- Richard M. Stallman


It's very simple - you read the protocol and write the code. -Bill Joy

>

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

+Askapache | htaccess.io | htaccess.guru

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service | @Htaccess

↑ TOPMain