WordPress has made huge improvements to the Media Library over time but one thing that has been lacking is the ability to add custom classes to image links as an option. Adding a class to an image link has many benefits, including but not limited to CSS styling or opening images inside of lightboxes or galleries. In this tutorial we will teach you how to dynamically add a custom class to image links in WordPress by utilizing PHP functions.

Dynamically Add a Custom Class to Image Links via a WordPress Function

In order to dynamically add a class to image links in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below. Make sure that you change where it says ‘YOUR-CLASS-HERE’ to whatever you want to name your custom class. Now, any new images with links inserted into a WordPress post via the Media Library will automatically have the custom class added to it.

PHP

function add_class_to_image_links($html, $attachment_id, $attachment) {
    $linkptrn = "/<a[^>]*>/";
    $found = preg_match($linkptrn, $html, $a_elem);
    // If no link, do nothing
    if($found <= 0) return $html;
    $a_elem = $a_elem[0];
    // Check to see if the link is to an uploaded image
    $is_attachment_link = strstr($a_elem, "wp-content/uploads/");
    // If link is to external resource, do nothing
    if($is_attachment_link === FALSE) return $html;
    if(strstr($a_elem, "class=\"") !== FALSE){ // If link already has class defined inject it to attribute
        $a_elem_new = str_replace("class=\"", "class=\"YOUR-CLASS-HERE", $a_elem);
        $html = str_replace($a_elem, $a_elem_new, $html);
    }else{ // If no class defined, just add class attribute
        $html = str_replace("<a ", "<a class=\"YOUR-CLASS-HERE\" ", $html);
    }
    return $html;
}
add_filter('image_send_to_editor', 'add_class_to_image_links', 10, 3);

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.

Share This