Remove mod rewrite from media attachment URL
-
Now I have this
http://site.com/news/test123.html/1581b8160394456a1a59b2c79fa13b4eI want to change it to this
http://site.com/?attachment_id=12345I want to off mod-rewrite but only for media attachments
-
Hi wildapache, you can keep pretty permalinks for your posts and pages and change only the attachment URLs. WordPress lets you override the URL it generates for attachment pages with the attachment_link filter. Add this to a child theme’s functions.php (or a small custom plugin, so a theme update does not remove it):
add_filter( 'attachment_link', function( $link, $post_id ) {
return home_url( '?attachment_id=' . $post_id );
}, 10, 2 );The plain ?attachment_id= URLs still resolve fine with pretty permalinks enabled, because WordPress parses that query variable directly. Your posts and pages keep their /news/…/ addresses, while attachment links become /?attachment_id=12345. One thing to check afterwards: some gallery or lightbox plugins build attachment URLs themselves and skip this filter, so verify the media links on your site once it is in place.
Hi @wildapache,
You don’t have to disable
mod_rewritecompletely. You can keep your normal pretty permalinks and change only the attachment URLs.Try adding this to your child theme’s
functions.phpor a small custom plugin:add_filter( 'attachment_link', function( $link, $post_id ) { return home_url( '?attachment_id=' . $post_id ); }, 10, 2 );This will make attachment URLs like:
http://site.com/?attachment_id=12345while your posts and pages will continue using their normal pretty URLs.
Just keep in mind that some gallery or lightbox plugins may generate attachment URLs themselves, so it’s worth testing those after adding the code.
Thanks,
It works !
You must be logged in to reply to this topic.