Could you please help me to prefix attachment permalinks with a custom string (for example attachment)

Such that example.com/attachment-slug becomes example.com/attachment/slug?

  • Apply only to posts with post_type attachment
  • Using PHP that can be added to a custom plugin / mu-plugin / functions.php
  • Don’t worry about existing attachments – the code should alter the permalinks of new attachments

Thank you.

Kind regards, Mat

P.S. Related question here

  • Is the requirement that only new attachments be modified necessary? It makes the question much harder to solve – Tom J Nowell Aug 11 at 15:37
  • On closer inspection, if an attachment is attached to a post, it's permalink is example.com/...../post-slug/attachment-slug, there are questions/articles on changing individual attachment slugs via the UI. i believe this can be done with a rewrite rule and an adjustment to the permalink via a filter to point to the new rewritten URL – Tom J Nowell Aug 11 at 15:40
  • Only for new attachments. – Mat Ej Aug 11 at 16:17
  • Thank you. I found a couple of functional (I tested it) examples for changing standard post permalinks that use add_filter('pre_post_link',... but nothing works with non-post type of posts. – Mat Ej Aug 11 at 16:20
  • those filters don't change the permalink, they just change the URL WP thinks the post is at, it doesn't mean that WP will handle that URL. You could use those filters to change the posts URL to I'm a little teapot short and stout, here's my handle here's my spout, that doesn't mean WP's permalinks and rewrite rules were changed. Think of it like telling people you have a new address to send post to, it doesn't work if you don't physically move to the new address. – Tom J Nowell Aug 11 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.