我想用 Bootstrap 3 制作一个响应式主题。但是,我需要自动将 CSS 类 .img-responsive
添加到每个帖子图像,因为我需要图像是响应式的。
请建议我需要在 WordPress 的 functions.php
文件或任何其他允许我自动添加 CSS 类的文件中添加什么。
最佳答案
因为你需要为你的所有帖子图片都使用它,所以你需要为内容添加一个钩子(Hook)并添加
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;
}
现在给内容添加钩子(Hook)
add_filter ('the_content', 'add_responsive_class');
但是,如果您已经有 img 的类并且需要添加一个新类,那么您可以引用 PHP equivalent to jQuery addClass .或者,您可以简单地这样做:
$existing_class = $img->getAttribute('class');
$img->setAttribute('class', "img-responsive $existing_class");
上面的代码有效.. 我用它来删除 src 和 data-src 以进行图像延迟加载。希望对你有用
关于css - 如何在图像中为 wordpress 帖子添加自动类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473004/