Add an img class to images inserted from URL
-
Hi, I’m struggling a bit with a problem related to images inserted “from URL”.
For some reason, I’m trying to add a “nolightbox” class to medias inserted in posts/pages when they’re linked to “Custom URL”.
I found here and there and adapted some php lines that I put in my child theme functions.php file:
function add_class_to_image_links($html, $attachment_id, $attachment) { $linkptrn = "/<a[^>]*>/"; $found = preg_match($linkptrn, $html, $a_elem); // If link (else just return) if($found > 0){ $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 not to internal resource if($is_attachment_link === FALSE){ $classes = 'nolightbox'; if ( preg_match('/<img.? class=".?">/', $html) ) { $html = preg_replace('/(<img.? class=".?)(".\?>)/', '$1 ' . $classes . '$2', $html); } else { $html = preg_replace('/(<img.*?)>/', '$1 class="' . $classes . '" >', $html); } } } return $html; } add_filter('image_send_to_editor', 'add_class_to_image_links', 10, 3);
It works fine so far with media from the gallery but not for media inserted “from URL”. And most of the media with a link to some external website is inserted from URL on this blog.
So I guess ‘image_send_to_editor’ is not the correct hook and/or method, but I’m no dev and don’t know what to do then (apart upload media to the gallery instead of getting them from their URL).
And this is just the 1st part of the problem, cause when I know how to add this class to images in newly created posts I have to find out the way to update 100s of already posted images before… That’s another story.
- The topic ‘Add an img class to images inserted from URL’ is closed to new replies.