Skip to content

Instantly share code, notes, and snippets.

@barbotkin
Last active February 7, 2017 15:45
Show Gist options
  • Save barbotkin/8772d60ba7e5b7e7fc5794e28116ac21 to your computer and use it in GitHub Desktop.
Save barbotkin/8772d60ba7e5b7e7fc5794e28116ac21 to your computer and use it in GitHub Desktop.
Add Custom class image (in the_content attached images) - Wordpress
<?php
// Input:
// <img src="...">
// Output:
// <a href="../wp-content/uploads/2016/09/2016-012_0005.jpg" data-lightbox="roadtrip">
// <img src=".../wp-content/uploads/2016/09/2016-012_0005-150x150.jpg" alt="2016-012_0005" width="150" height="150" class="custom-class alignleft size-thumbnail wp-image-1048">
// </a>
function custom_class_image($content){
$content = preg_replace('/<img (.*) \/>\s*/iU', '<a href="" data-lightbox="roadtrip"><img \1 /></a>', $content);
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
foreach ($document->getElementsByTagName('img') as $k => $img) {
$src = $img->getAttribute('src');
// Add custom class.
// $existing_class = $img->getAttribute('class');
// $img->setAttribute('class', 'custom-class '.$existing_class);
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => get_the_ID(),
);
// Get the attached images.
$attachments = get_posts( $args );
$img->parentNode->setAttribute('href', $attachments[$k]->guid);
}
$html = $document->saveHTML();
return $html;
}
add_filter('the_content', 'add_responsive_class');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment