I have several hundred posts which include a mix of single image and gallery blocks. All of them currently link to media file. What's the fastest way to change this to attachment page instead? (And back to media file, as an "undo")?

I found this but for some reason the answer selected has negative votes which makes me unsure about running it. It is also only for gallery blocks but not single image blocks. How to link Gutenberg Gallery images To Media file automatically?

  • The answer you've linked to wouldn't do what you need. It creates a block template, so that whenever you add a new Post, it adds a Gallery block linked to media. It can't affect any existing Posts, and is specific to the Gallery block.
    – WebElaine
    Jan 28, 2020 at 21:25

1 Answer 1


Fastest way in my opinion would be to apply filter on the_content with preg_replace_callback to find media URLs and replace them with anything else, like attachment pages. Attachment ID is available as part of <img> class value as well as wp:image attribute in Gutenberg comment. So you just need some smart regexp to match each image block in content and replace it. No undo needed. However this is maybe not the best solution performance wise, as replacents will be done on each page request (unless caching is used).

Better solution would be to run some PHP code once (wp-cli command or otherwise) to loop over all posts and replace post_content value with replaced URLs. Save DB backup before this for undo or create reverse replacement function as well.

  • Yes - these would both accomplish the goal, and you're right that a run-once scenario would be much better for performance. However, filtering the content would ensure that if any new Posts are added later, they also link to the right place - so there are pros and cons to both.
    – WebElaine
    Jan 28, 2020 at 21:27
  • Any chance you could improve this answer by adding the "better solution" you mention? It sounds very helpful!
    – rythos42
    Aug 16, 2020 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.