Append a Trailing Slash to Paths and URLs
There are cases when you need to append other things to some paths or URLs but end up breaking them because of missing slashes. This is especially true if you get those paths and URLs from untrusted sources (e.g. user inputs) or unsupported sources (e.g. other plugins). Using the magic function trailingslashit() you will no longer have to worry about that issue:
- /**
- * Appends a trailing slash.
- *
- * Will remove trailing slash if it exists already before adding a trailing
- * slash. This prevents double slashing a string or path.
- *
- * The primary use of this is for paths and thus should be used for paths. It is
- * not restricted to paths and offers no specific path support.
- *
- * @since 1.2.0
- * @uses untrailingslashit() Unslashes string if it was slashed already.
- *
- * @param string $string What to add the trailing slash to.
- * @return string String with trailing slash added.
- */
- function trailingslashit($string) {
- return untrailingslashit($string) . '/';
- }
/**
* Appends a trailing slash.
*
* Will remove trailing slash if it exists already before adding a trailing
* slash. This prevents double slashing a string or path.
*
* The primary use of this is for paths and thus should be used for paths. It is
* not restricted to paths and offers no specific path support.
*
* @since 1.2.0
* @uses untrailingslashit() Unslashes string if it was slashed already.
*
* @param string $string What to add the trailing slash to.
* @return string String with trailing slash added.
*/
function trailingslashit($string) {
return untrailingslashit($string) . '/';
}The description in the snippet above should have explained clearly to you what that function does. Now to actually use it, just pass any paths or URLs you are unsure about validity and trailingslashit() will ensure that those paths and URLs will always have a trailing slash at the end (and no double slashing will occur).
There is a somewhat similar function called user_trailingslashit() that allows you to add the trailing slash based on your permalink structure. You can read more about that function here.








This is super! I always get stuck with missing slashes that ruins everything…
Thank you.