当我向帖子中添加图像时,我希望它位于div中,例如,我希望它自动完成,所以我不必在HTML编辑器中这样做。我不想使用js来实现这一点,顺便说一下,我想知道如何在帖子中自动向图像添加自定义类。干杯
如何用div将帖子中的每一张图片包装起来?
默认情况下,图像已经具有唯一类,但这取决于主题。使用firebug并将鼠标悬停在图像上,您应该可以看到如下内容class="aligncenter size-full wp-image-1525"
.
如果要更改类或id或更改图像的任何属性,可以使用get_image_tag
滤器例如
add_filter(\'get_image_tag_class\',\'my_custom_class\');
function my_custom_class($class){
$class=\'my_custom_name\';
return $class;
}
在进行一些研究时,我发现了以下代码。您可以使用WordPress的内置过滤器轻松地将帖子图像包装到Div中,即image_send_to_editor. 下面是一个例子,
if( is_admin() ) {
add_filter( \'image_send_to_editor\', \'wp_image_wrap_init\', 10, 8 );
function wp_image_wrap_init( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
return \'<div id="wp-image-wrap-\'. $id .\'" class="wp-image-wrap">\'. $html .\'</div>\';
}
}
感谢http://wpalkane.com/hacks/wrap-post-image-inside-div-automatically/您的答案很接近,但还不够,因为get\\u image\\u标记的钩子检查点_class() 仅更改class属性。因此,我四处游荡,发现包装每个图像的正确方法是get_image_tag() 所以代码是这样的:
function my_image_tag($html, $id , $alt, $title){
$html = "<div class=\'**wrap-div**\'>" . $html . "</div>";
return $html;
}
add_filter(\'get_image_tag\',\'my_image_tag\',10,4);
您的回答部分正确,因此这是最好的;)干杯,伙计,谢谢你的帮助。这里的答案可以分为两种方法:
1) functions, that work in POST EDITOR (back-end) (参见张贴的答案)
2) functions, that work in POST OUTPUT (front-end)
p、 改变前端输出的另一种方法:
(a)
function my_image_class_filter($classes) {
return $classes . \' another-image-class\';
}
add_filter(\'get_image_tag_class\', \'my_image_class_filter\');
(b)function add_post_image_class($content) {
return preg_replace(\'/<img(.*?)class="(.*?)"/\', \'<img $1 class="$2 YOUR_CLASS_NAME"\', $content);
}
add_filter( \'the_content\', \'add_post_image_class\' );