Like always is WordPress, there is a filter to do this, without the need of a regular expression, that might fail if anything changes.
Here is the code for the output:
<?php
add_filter('wp_get_attachment_image_attributes', function($attr, $attachment){
unset($attr['alt']); // Just deleting the alt attr
return $attr;
}, 10, 2);
$url = wp_get_attachment_url( $attachment->ID );
$name = esc_attr( $attachment->post_title );
$title = wptexturize($attachment->post_excerpt);
$text = wp_get_attachment_image( $id, $size, false );
if ( trim( $text ) == '' )
$text = $attachment->post_title;
$link = "<a href="https://wordpress.stackexchange.com/questions/65982/$url"" . (!empty($rel)? " rel="$rel"":"") . " title="$title" name="$name">$text</a>";
It’s faster because saves up time because you already have the $attachment
object, and wp_get_attachment_link
retrieves it again, even if it’s cached in memory it’s better not to do it.
Replace the code, with the one above, and don’t forget to put the add_filter
before the loop, so you do have a overhead of creating multiple times the same filter.
$link = wp_get_attachment_link($id, $size, true, false);
if( ! empty($rel) ) { // !!! Add rel injection
$link = str_replace('<a href="https://wordpress.stackexchange.com/questions/65982/,"<a rel="$rel' href=" .wp_get_attachment_url( $attachment->ID ). " alt=", $link);
} else {
$link = str_replace('<a href="https://wordpress.stackexchange.com/questions/65982/,"<a rel="$rel' href=", $link);
}
$link = str_replace("title=""https://wordpress.stackexchange.com/questions/65982/,"title="" . wptexturize($attachment->post_excerpt) . "' name="", $link);