如何添加自动类在imagepress的WordPress的帖子 [英] How to add automatic class in image for wordpress post

查看:89
本文介绍了如何添加自动类在imagepress的WordPress的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Bootstrap 3做一个响应主题。但是,我需要自动添加CSS类 .img-responsive 到每个帖子图像,因为我需要图像



请向我建议我需要在WordPress的 functions.php 文件或任何其他文件中添加这将允许我自动添加CSS类。

解决方案

因为你需要有它的所有发布图像,您需要为内容添加一个钩子并添加

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

$ html = $ document-> saveHTML();
return $ html;
}

现在将内容添加到内容

  add_filter('the_content','add_responsive_class');但是,如果你已经有了img的类,你需要添加一个新的类,那么你可以请参阅等价于jQuery addClass 的PHP。或者,您可以这样做:

  $ existing_class = $ img-> getAttribute('class'); 
$ img-> setAttribute('class',img-responsive $ existing_class);

上面的代码工作..我使用它来删除src和data-src图像延迟加载。希望它为您工作


I want to make a responsive theme with Bootstrap 3. However, I need to automatically add the CSS class .img-responsive to every post image because I need the images to be responsive.

Please suggest me what I need to add in WordPress's functions.php file or any other file that will allow me to add the CSS class automatically.

解决方案

since you need to have it for all of your post images, then you need to add a hook for the content and add

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

        $html = $document->saveHTML();
        return $html;   
}

now add the hook to the content

add_filter        ('the_content', 'add_responsive_class');

However, if you already have classes for the img and you need to add a new class then you can refer to PHP equivalent to jQuery addClass. Or, you can simply do this:

$existing_class = $img->getAttribute('class');
$img->setAttribute('class', "img-responsive $existing_class");

The code above works .. i use it to remove src and data-src for image lazy loading. Hope it works for you

这篇关于如何添加自动类在imagepress的WordPress的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆