css - 如何在图像中为 wordpress 帖子添加自动类

标签 css wordpress twitter-bootstrap-3 wordpress-theming

我想用 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/

相关文章:

html - 3 个内联 block div,宽度刚好为 33%,不适合父级

css - 如何在 JavaFX CSS 中创建自定义边框样式?

css - Bootstrap 3 : Two collapsable navabrs with fixed-top?

javascript - Angular 范围和应用的 css 类仅在第一个 div 上

css - SASS/Compass Math 使用动态宽度

css - 从子主题中删除样式

javascript - jQuery 滚动功能不起作用

php - WooCommerce Hook before "New Order"- 邮件已发送

javascript - 在 Polymer 中使用 Bootstrap 的工具提示

css - Bootstrap 3 @font-size-base 在手机上变大