如何在wordpress帖子的图像中添加自动类 [英] How to add automatic class in image for wordpress post
问题描述
我想使用 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();返回 $html;}
现在给内容添加钩子
add_filter('the_content', 'add_responsive_class');
但是,如果你已经有 img 的类并且你需要添加一个新的类,那么你可以参考 PHP 相当于 jQuery addClass.或者,您可以简单地执行以下操作:
$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
这篇关于如何在wordpress帖子的图像中添加自动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!