Ami*_*ker 14 css wordpress wordpress-theming twitter-bootstrap-3
我想用Bootstrap 3制作一个响应主题.但是,我需要自动将CSS类添加.img-responsive
到每个帖子图像,因为我需要图像响应.
请建议我在WordPress的functions.php
文件或任何其他文件中添加我需要自动添加CSS类的内容.
Ahm*_*saf 42
因为您需要为所有帖子图像提供它,所以您需要为内容添加一个钩子并添加
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;
}
Run Code Online (Sandbox Code Playgroud)
现在添加钩子到内容
add_filter ('the_content', 'add_responsive_class');
Run Code Online (Sandbox Code Playgroud)
但是,如果你已经有了img的类,你需要添加一个新类,那么你可以引用相当于jQuery addClass的PHP.或者,你可以简单地这样做:
$existing_class = $img->getAttribute('class');
$img->setAttribute('class', "img-responsive $existing_class");
Run Code Online (Sandbox Code Playgroud)
上面的代码工作..我用它来删除src和data-src图像延迟加载.希望这对你有用
Yar*_*ron 28
这种方法更好:https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image
function add_image_class($class){
$class .= ' additional-class';
return $class;
}
add_filter('get_image_tag_class','add_image_class');
Run Code Online (Sandbox Code Playgroud)
唯一需要注意的是,它会在您插入新图像时在编辑窗格中添加该类,并且不会影响现有图像.
Syc*_*one 15
我认为最简单的方法是使用这样的CSS.
.content img { height: auto; max-width: 100%; }
Run Code Online (Sandbox Code Playgroud)
where .content是包含您的帖子内容的区域.
注意:您可能还想覆盖.wp-caption类,就像这样.
.wp-caption { width: auto !important; }
Run Code Online (Sandbox Code Playgroud)
小智 11
我有同样的问题,并将此函数添加到functions.php为我工作.
function add_image_responsive_class($content) {
global $post;
$pattern ="/<img(.*?)class=\"(.*?)\"(.*?)>/i";
$replacement = '<img$1class="$2 img-responsive"$3>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'add_image_responsive_class');
Run Code Online (Sandbox Code Playgroud)
当您在循环中显示帖子时,您可以:
the_post_thumbnail('thumbnail', array('class' => 'img-responsive'));
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅https://codex.wordpress.org/Function_Reference/the_post_thumbnail.
归档时间: |
|
查看次数: |
38597 次 |
最近记录: |