繁体   English   中英

添加类img-响应wordpress中所有附加的帖子图像

[英]add class img-responsive to all attached post images in wordpress

我想将class = img-responsive和img-shadow添加到所有附加的帖子缩略图中,我使用以下功能可以正常工作,但它删除了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;   
}

但是我想合并我的课程而不仅仅是覆盖它们,所以我用了jQuery

 jQuery(function() {
jQuery(img).addClass('img-responsive img-shadow ');
});

但它给错误jquery未定义

请帮帮我

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');

为什么不随便用函数重新添加原始类呢?

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;   
}

如果使用上面提到的DOMDocument方法,这可能会导致utf编码出现问题,尤其是在通过内容编辑器使用特殊字符时,例如:£转换为? 或其他奇怪的字符。 您可以遍历$ img,然后在$ content上使用str_replace,但是使用“ terminators”方法对我来说要好得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM