Back to Top

Append a Trailing Slash to Paths and URLs

Previous Post:

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) . '/';

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.

Take Social Sharing to
the Next Level with Monarch!

Take Social Sharing to the Next Level with Monarch!
Print Article Trackback Trackback to this Article   Subscribe to Comments RSS Subscribe to Comments RSS

2 Opinions for Append a Trailing Slash to Paths and URLs (1 Trackback)

  1. User's Gravatar
    kay January 18, 2012 at 8:01 pm – Permalink

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

  1. Ten Useful WordPress Constants You Might Love - Better WordPress

    […] and STYLESHEETPATH do not have a trailingslash (i.e. /), so it is recommended that you use trailingslashit along with these two […]

Speak Up Your Mind!

An asterisk (*) indicates a required field and must be filled.

  • Web page and e-mail addresses turn into links automatically.
  • Wrap codes in: <code lang=""></code> or <pre lang="" extra="">
  • Lines and paragraphs break automatically.

Next Post: