WordPress has two functions that can be helpful when dealing with the final character of a URL, trailingslashit() and untrailingslashit(). I find it preferable to use untrailingslashit()
for two reasons: 1. It does not break empty checks and 2. It makes my sprintf()
statements more readable.
Empty Check
If we are checking for an empty value, untrailingslashit()
will NOT throw off our result.
$my_url = untrailingslashit( get_option( 'my_url' ) );
if ( ! $my_url ) {
// $my_url is an empty string, Return early.
return;
}
// Do thing with $my_url here.
If we used trailingslashit()
in the above example instead, the if
conditional check will always be true because even if the my_url
option is an empty string (""
), then $my_url
will be "/"
. In other words, by using trailingslashit()
the value of $my_url
will never be an empty string.
sprintf
Using untrailingslashit()
makes lines with sprintf()
more readable.
Example:
$base_url = 'https://salferrarello.com/';
$full_url = sprintf(
'%s/wp-json/wp/v2/posts',
esc_url( untrailingslashit( $base_url ) )
);
I prefer the sprintf()
template string
'%s/wp-json/wp/%s/posts'
to the alternative if we use trailingslashit()
, which would be %swp-json/wp/%s/posts
(where %s
and wp-json
are next to each other with no separator).
Further clarification on how trailingslashit() and untrailingslashit() work
The trailingslashit()
function ensures the final character is a slash (/
).
echo trailingslashit( 'http://salcode.com' );
# outputs "http://salcode.com/"
# since there was no trailing slash, it adds one
echo trailingshlashit( 'http://salcode.com/' );
# outputs "http://salcode.com/"
# since there was already a trailing slash, no changes are made
The untrailingslashit()
function does exactly the opposite, ensuring the final character is NOT a slash (/
).
echo untrailingslashit( 'http://salcode.com/' );
# outputs "http://salcode.com"
echo untrailingslashit( 'http://salcode.com' );
# outputs "http://salcode.com"
Leave a Reply