Wordpress - add media category class to image on inserting into WP Editor
//add category class to img tag when adding media
function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
$classes = '';
if (has_term('','att_tax',$id)) {
$terms = wp_get_post_terms($id, 'att_tax');
if ($terms) {
foreach ($terms as $term) {
$classes .= $term->slug.' '; // separated by spaces, e.g. 'img image-link'
}
}
}
// check if there are already classes assigned to the anchor
if ( preg_match('/<a.*? class=".*?">/', $html) ) {
$html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
} else {
$html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $html);
}
return $html;
}
add_filter('image_send_to_editor','give_linked_images_class',10,8);