There are two parts to URLs in WordPress-
One part is the output of URLs for any given content. To change how these are output, you need to filter them. This is what your attachment_link
filter does.
The other part is how WordPress determines what content requested URLs should load. This is the part you’re missing- WordPress still expects these requests to contain attachment
, not your new word.
To fix that, you can filter the rewrite rules that WordPress generates, and replace attachment
with whatever unique thing you want:
function wpd_rename_attachment_rewrites( $rules ){
foreach( $rules as $key => $value ){
$new_key = str_replace( 'attachment', 'new-word', $key );
unset( $rules[ $key ] );
$rules[ $new_key ] = $value;
}
return $rules;
}
add_filter( 'rewrite_rules_array', 'wpd_rename_attachment_rewrites' );
EDIT-
The attachment_link
function in your question ignores the original value of $link
, and just returns a URL in a fixed pattern:
function wpd_attachment_link( $link, $post_id ){
$post = get_post( $post_id );
return home_url( '/images/' . $post->post_title );
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );
Change that to replace attachment
within the value passed as $link
instead, preserving the rest of the original URL:
function wpd_attachment_link( $link, $post_id ){
return str_replace( '/attachment/', '/new-word/', $link );
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );