How to Customize the URL of Attachments in WordPress
Using a custom URL structure for attachment pages gives a nice touch to your website.
Problem
You need to create a custom URL structure for attachments. The slug of each attachment must end with a suffix, so the slug derived from the filename remains free.
Example: If you upload the file Landscape.png to the Media Library, the URL of the attachment page should be https://example.com/media/landscape-dl.
Theory
In the next section I propose a solution that uses the 'rewrite_rules_array'
filter to add a rewrite rule, so WordPress knows how to process the custom URL structure.
The 'attachment_link'
filter is used to customize the attachment URL according to the new structure. The 'wp_insert_attachment_data'
filter is used to append a suffix to the slug if the suffix is not present yet.
Steps
Follow these steps to solve the problem described previously.
Step 1: Add the code below to WordPress. Adjust the variables $dirname
and $suffix
as desired.
Step 2: Navigate to Settings > Permalinks. Click Save Changes to flush rewrite rules.
Step 3: Upload a file to the Media Library and visit the attachment page. Verify that the URL is as expected.
Discussion
Each attachment is now accessible through the custom URL and the default URL works too. There is no risk from an SEO viewpoint since WordPress sets the canonical URL to the custom URL.
Attachments created before this change will not have the suffix in the slug. If you want the suffix in these attachments, open the edit screen of each one and click the Update button. Note that existing links may get broken.
Further reading
I recommend the other tutorials in this series to learn more about managing attachments in WordPress.
- Big Image Handling in WordPress
- How to Restrict the Maximum Upload Size in WordPress
- How to Increase the Maximum Upload Size in WordPress
- How to Change the Upload Directory in WordPress
- How to Move the Upload Directory to a Subdomain in WordPress
- How to Force File Download in WordPress
- How to Disable Attachment Pages in WordPress
- How to Customize the URL of Attachments in WordPress
Source code
The source code developed in this tutorial is available here.
Comments