如果您只想将所有图像设为 100%,那么在您的 CSS 样式表中执行此操作可能更合适。
如果您需要自定义 WP 编辑器(使用 TinyMCE 编辑器),有几种方法可以做到这一点,具体取决于您想要什么。您问题中的描述和代码不匹配,所以我在下面给出了两个选项:
1.在编辑器工具栏中添加“自定义样式”下拉菜单
您问题中的代码是您用来添加自定义样式下拉列表的代码,类似于默认样式(段落、标题 1 等)。您可以使用以下代码对您的functions.php
.
这将添加一个名为“格式”的下拉菜单,其中包含 2 个选项 - 一个直接在图像上添加样式,另一个向图像添加自定义类(这是更可取的,因为它为您提供了更大的灵活性):
1. Set up the custom styles in the TinyMCE Editor settings
function my_mce_insert_custom_styles( $settings) {
// Create your array of custom styles to add
$style_formats = array(
// 1. OPTION TO ADD STYLE DIRECTLY TO THE IMAGE
array(
'title' => '100% Width Image Style',
'selector' => 'img',
'styles' => array( 'width' => '100%' )
),
// 2. OPTION TO ADD A CLASS TO THE IMAGE
array(
'title' => 'Add My Class to Image',
'selector' => 'img',
'classes' => 'my_image_class',
)
);
// Add the array the 'style_formats' setting
$init_array['style_formats'] = json_encode( $style_formats );
return $init_array;
}
add_filter( 'tiny_mce_before_init', 'my_mce_insert_custom_styles' );
// 2. Add custom styles to the 2nd toolbar of your Wordpress editor
function my_mce_buttons_2($buttons) {
array_unshift($buttons, 'styleselect');
return $buttons;
}
add_filter('mce_buttons_2', 'my_mce_buttons_2');
现在将在编辑器的第二个工具栏中有一个额外的“格式”下拉菜单。选择图像时,您可以选择上述任一格式以应用于图像。
2.自动为插入的图片添加样式/类
即使您使用的是上面的代码,您的描述听起来就像您想自动应用样式一样。
您可以通过将以下内容添加到您的functions.php
. 同样,我提供了将样式直接添加到图像或添加类的选项 - 您可以删除不需要的选项:
function my_custom_image_styling($html, $id, $caption, $title, $align, $url, $size, $alt) {
$doc = new DOMDocument();
$doc->loadHTML($html);
$imgs = $doc->getElementsByTagName('img');
foreach($imgs as $img){
// 1. ADD THE STYLE ATTRIBUTE DIRECTLY TO THE IMAGE
$styles = $img->getAttribute("style");
$img->setAttribute("style", $styles."width:100%;");
// OR 2. ADD A CLASS TO THE IMAGE
$classes = $img->getAttribute("class");
$img->setAttribute("class", $classes." my_image_class");
}
$html = $doc->saveHTML();
return $html;
}
add_filter('image_send_to_editor', 'my_custom_image_styling', 1, 8);
现在,根据您使用的行,样式或类将在插入编辑器时自动添加到图像中。
参考