While working on the latest version of Standard For WordPress.com, Michael – who covers QA at 8BIT – caught an interesting problem with how our breadcrumb navigation and archive page templates were working (or weren’t working):
The Nature of Permalinks
When you’re building anything for WordPress that relies on a certain URL structure, you have to account for the fact that there are a variety of ways for displaying URLs.
Generally, this is reduced to permalinks and pretty permalinks:
- Vanilla permalinks are usually of the form: http://tommcfarlin.com/?p=100
- Pretty permalinks are of the form: http://tommcfarlin.com/user_trailingslashit
Basically, non-pretty permalinks send data that looks more computer-friendly than human-readable to send data, whereas pretty permalinks send data that looks more human readable.
The Problem with Permalinks
Since certain blogs are written by a variety of authors, we do what we can to make sure that we display the author’s name when appropriate.
This includes places such as the breadcrumb trail and the author archives page:
In the picture above, notice that there is no ‘/’ at the end of the URL. Also notice that Michael’s name appears in both the breadcrumb trail and the archives label.
But if you were to navigate to the same URL with a trailing slash, this is what you’d see:
When the trailing slash is added, the name of the author disappears.
Originally, the code for retrieving the user’s name based on the URL looked like this:
// Get the author data based on the author ID in the URL $author_data = get_userdata( get_query_var( 'author' ) ); // Get the author's name from the author data $author_data->display_name
This only works if there is no trailing slash in the URL. To fix, I added a call to
user_trailingslashit in the first line of code above:
// Get the author data based on the author ID in the URL $author_data = get_userdata( user_trailingslashit( get_query_var( 'author' ) ) );
And that resolved the issue.
Simply put, user_trailingslash it forces the URL to be consistent with what the user has set in his/her permalink preferences.
For those that are curious, you can read the documentation for the function in
wp-includes/link-template.php which says:
/** * Retrieve trailing slash string, if blog set for adding trailing slashes. * * Conditionally adds a trailing slash if the permalink structure has a trailing * slash, strips the trailing slash if not. The string is passed through the * 'user_trailingslashit' filter. Will remove trailing slash from string, if * blog is not set to have them. * * @since 2.2.0 * @uses $wp_rewrite * * @param string $string URL with or without a trailing slash. * @param string $type_of_url The type of URL being considered (e.g. single, category, etc) for use in the filter. * @return string */
Simple enough, isn’t it? This was definitely new for me.