Do you want to add a custom class to the links of all your attachments? Attachments displayed on your blog will be inside this <a> tag link.
There is an easy way to add a custom class to all your attachment links without having to make changes to every place in your theme’s code where an attachment is displayed. You can do so by adding a filter to the wp_get_attachment_link function. This function is called to get the link (<a> tag) for the attachment that will be displayed.
Add this code to your theme’s functions.php file or create a custom plugin with this code:
function add_custom_class_attachment_link($html){
$html = str_replace('<a', '<a class="my_custom_attachment_link_class"', $html); // Add class to the original anchor tag.
return $html;
}
add_filter('wp_get_attachment_link', 'add_custom_class_attachment_link', 10, 1);
The above code simply adds a filter to the wp_get_attachment_link function. Whenever this function is called, our custom function will be called before this function outputs the links. This way we get to modify the links on the fly.
Replace my_custom_attachment_link_class with whatever class name you want to give the attachment links.
Leave a Reply