i want to add class=img-reponsive & img-shadow to all the attached post thumbnail i used following function which works fine but it removes the original classes of thubmails
function add_responsive_class($content){
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$img->setAttribute('class','img-responsive img-shadow');
}
$html = $document->saveHTML();
return $html;
}
But i want to merge my classes not just overwrite them So i used jquery
jQuery(function() {
jQuery(img).addClass('img-responsive img-shadow ');
});
But its giving error jquery not defined
Please help me out
function add_image_responsive_class($content) {
global $post;
$pattern ="/<img(.*?)class=\"(.*?)\"(.*?)>/i";
$replacement = '<img$1class="$2 img-responsive img-shadow"$3>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'add_image_responsive_class');
Why dont you just re-add the original class with your function?
function add_responsive_class($content){
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$img->setAttribute('class','thumbnails img-responsive img-shadow');
}
$html = $document->saveHTML();
return $html;
}
If you are using the DOMDocument method mentioned above, this can cause issues with utf encoding, especially when using special characters through your content editor, for example: £ being convered to ? or other strange characters. You can loop through $img and then use str_replace on $content, but using "terminators" method worked far better for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.