If you want to add a trailing slash to the URL in WordPress, this can be done using the redirect_canonical
filter. Here’s an example code snippet to add a trailing slash to URLs:
function wpsnippets_add_trailing_slash( $redirect_url ) {
return trailingslashit( $redirect_url );
}
add_filter( 'redirect_canonical', 'wpsnippets_add_trailing_slash' );
In this code snippet, we define a function wpsnippets_add_trailing_slash()
that takes the original redirect URL as a parameter and add a trailing slash using the trailingslashit()
function. We then return the modified URL to the redirect_canonical
filter.
By adding this code snippet to your WordPress site, URLs without a trailing slash will be redirected to the same URL with a trailing slash, which can be useful for SEO purposes and for ensuring that URLs are consistent throughout your site.
Note that if your WordPress site is using a caching plugin, you may need to clear the cache after adding this code snippet to ensure that the redirects are applied correctly.
Alternative method: Modifying the .htaccess file
Instead of using the above code snippet, you can also add a trailing slash to URLs by modifying the .htaccess file, following these steps:
- Access your WordPress website’s root directory via FTP or File Manager in cPanel.
- Find the .htaccess file and download it to your computer as a backup.
- Open the .htaccess file in a text editor.
- Add the following code at the beginning of the file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)([^/])$ $1$2/ [L,R=301]
- Save the changes and upload the modified .htaccess file back to your website’s root directory.