Custom permalink for attachment

I am trying to rewrite my permalinks for attachments, which would open the attachment.php post. I found some code from this answer and have modified it to look like this:

function wpd_attachment_link( $link, $post_id ){
$mimes = array( ‘image/jpeg’, ‘image/gif’, ‘image/png’, ‘image/bmp’, ‘image/tiff’, ‘image/x-icon’ );
$post = get_post( $post_id );
if ( in_array( $post->post_mime_type, $mimes ) ){
return home_url( ‘/images/’ . $post->post_name . ‘/’ );
} else {
return home_url( ‘/files/’ . $post->post_name . ‘/’);
add_filter( ‘attachment_link’, ‘wpd_attachment_link’, 20, 2 );

What I intend to do is have all images open with an images URL and all other files to open with a files URL. I am setting up the attachment.php page to fit my design, but the page does exist. Before I used the attachment_link filter, I could see the page. Now, the new URL format returns a 404 error, and the old URL format (standard post URL with the attachment’s post_name variable appended) redirects to the new URL, which returns a 404 error. Is there a way where I can display the required page with /images/ and /files/?

Read more here:: Custom permalink for attachment

Leave a Reply

Your email address will not be published. Required fields are marked *