add_editor_style()
概述
add_editor_style() 函数用于为 TinyMCE 可视化编辑器注册自定义样式表,支持主题开发者链接 CSS 文件以定制编辑器外观。它自动处理 RTL 样式,并兼容子主题和 Gutenberg 编辑器。
关键要点
- 函数接受字符串或数组参数,指定相对于主题根目录的样式表路径,默认使用 'editor-style.css'。
- 自动添加 RTL 样式表(如 editor-style-rtl.css),若文件不存在则跳过;数组参数时仅对第一个样式表添加 RTL。
- 支持子主题,会同时检查子主题和父主题目录并链接找到的文件。
- 在 Gutenberg 编辑器中,样式作为内联样式添加,选择器前缀为 .editor-styles-wrapper,body 样式会被转换。
- 插件中使用时需提供绝对 URL,而非相对路径;可通过 mce_css Hook 替代实现非主题目录的样式链接。
- 动态样式可通过 tiny_mce_before_init 过滤器的 content_style 键添加。
- 注意:使用 admin_init Hook 调用时,需手动添加 add_theme_support('editor-styles') 以避免主题支持声明过晚。
代码示例
function wpdocs_theme_add_editor_styles() {
add_editor_style( 'custom-editor-style.css' );
}
add_action( 'admin_init', 'wpdocs_theme_add_editor_styles' );注意事项
- 本地开发时,使用绝对 HTTPS URL 可能因自签名证书失败,建议使用相对路径。
- 避免在样式表中使用 CSS @import,可能导致问题;可改用数组参数或独立加载。
- Gutenberg 编辑器早期版本不支持 CSS @layers,需注意兼容性。
- 字体文件路径需使用完整 URL,否则可能加载失败。
Adds callback for custom TinyMCE editor stylesheets.
Description
The parameter $stylesheet is the name of the stylesheet, relative to the theme root. It also accepts an array of stylesheets.
It is optional and defaults to ‘editor-style.css’.
This function automatically adds another stylesheet with -rtl prefix, e.g. editor-style-rtl.css.
If that file doesn’t exist, it is removed before adding the stylesheet(s) to TinyMCE.
If an array of stylesheets is passed to add_editor_style() , RTL is only added for the first stylesheet.
Since version 3.4 the TinyMCE body has .rtl CSS class.
It is a better option to use that class and add any RTL styles to the main stylesheet.
Parameters
$stylesheetarray|stringoptional-
Stylesheet name or array thereof, relative to theme root.
Defaults to'editor-style.css'
Source
function add_editor_style( $stylesheet = 'editor-style.css' ) {
global $editor_styles;
add_theme_support( 'editor-style' );
$editor_styles = (array) $editor_styles;
$stylesheet = (array) $stylesheet;
if ( is_rtl() ) {
$rtl_stylesheet = str_replace( '.css', '-rtl.css', $stylesheet[0] );
$stylesheet[] = $rtl_stylesheet;
}
$editor_styles = array_merge( $editor_styles, $stylesheet );
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 13 content
Codex
Basic Example
Add the following to the functions.php file of your theme.
/** * Registers an editor stylesheet for the theme. */ function wpdocs_theme_add_editor_styles() { add_editor_style( 'custom-editor-style.css' ); } add_action( 'admin_init', 'wpdocs_theme_add_editor_styles' );Next, create a file named custom-editor-style.css in your themes root directory. Any CSS rules added to that file will be reflected within the TinyMCE visual editor. The contents of the file might look like this:
body#tinymce.wp-editor { font-family: Arial, Helvetica, sans-serif; margin: 10px; } body#tinymce.wp-editor a { color: #4CA6CF; }add_editor_style()internally adds not the same theme supports string that you’ve meant to add manually. From the Editor styles docs, this is what you should add:add_theme_support( 'editor-styles' );. And this is what is called insideadd_editor_style()function:add_theme_support( 'editor-style' );. Notice the “missing” “s” character at the end.Skip to note 14 content
Code Muffin
# Gutenberg
This works with Gutenberg. Your CSS will be added as inline styles. All selectors will be prefixed with:
.editor-styles-wrapper(exceptbody, see below).All the info below is related to using this function with Gutenberg.
# Body Styles
Styles targeting the body will be changed to target
.editor-styles-wrapperinstead. This lets you to customise the Gutenberg editor pane directly, e.g. to change its padding. You can also set defaults (like font family, color, etc) by adding styles to the body class.Example:
body { color: red }becomes.editor-styles-wrapper { color: red }# CSS Resets
If you’re using the same stylesheet for both your frontend and editor styles, be careful about using a CSS reset. It will affect all elements within the editor, including admin controls for blocks ─ such as TinyMCE’s GUI buttons in the Classic block, or ACF block fields in edit mode.
You may prefer to move your reset of your main styles and enqueue it independently on the frontend instead, perhaps with a dedicated, customized reset for the editor.
# Using @import
I’ve seen developers report that using
@importin your CSS causes issues. If this happens to you, it would be better to add the imported file by other means, either as an additional array item inadd_editor_style, or by enqueuing it as an admin style on just editor pages (see other user notes that use$pagenowfor this).# Local Development + SSL
If you’re working locally, be aware that using an absolute URL (eg. via get_template_directory_uri) won’t work if you’re using HTTPS with a self-signed certificate. This is due to wp_remote_get being used to retrieve your stylesheet, which fails (silently) if a requested URL’s certificate isn’t included in WordPress’ internal store of allowed certificates.
Workarounds include: Using a path relative to your theme root instead (ideal), using an absolute HTTP URL instead of HTTPS, and disabling the SSL verification with https_ssl_verify (not recommended for security reasons).
# Code Context
The code that retrieves the styles uses either wp_remote_get for absolute URLs, or
file_get_contentsfor files relative to the theme root. You can find this code in block-editor.php, at the functionget_block_editor_theme_styles(). It’s called from edit-form-blocks.php.$relative_path = str_replace( WP_CONTENT_URL, '../..', $url ); add_editor_style( $relative_path );Skip to note 15 content
Tony Hayes
If you want to add styles dynamically (eg. from theme mods) you can use the tiny_mce_before_init filter and add them to the content_style key.
add_filter('tiny_mce_before_init','wpdocs_theme_editor_dynamic_styles'); function wpdocs_theme_editor_dynamic_styles( $mceInit ) { $styles = 'body.mce-content-body { background-color: #' . get_theme_mod( 'background-color', '#FFF' ) . '}'; if ( isset( $mceInit['content_style'] ) ) { $mceInit['content_style'] .= ' ' . $styles . ' '; } else { $mceInit['content_style'] = $styles . ' '; } return $mceInit; }Note that any new lines or double quotes should be removed or double escaped in your CSS.
Skip to note 16 content
Codex
Using Google Fonts
Google Fonts API provides a single URL for a CSS file that can include multiple variants of a type face, separated by commas. Commas in a URL need to be encoded before the string can be passed to add_editor_style.
/** * Registers an editor stylesheet for the current theme. */ function wpdocs_theme_add_editor_styles() { $font_url = str_replace( ',', '%2C', '//fonts.googleapis.com/css?family=Lato:300,400,700' ); add_editor_style( $font_url ); } add_action( 'after_setup_theme', 'wpdocs_theme_add_editor_styles' );Skip to note 17 content
Codex
Choosing Styles Based on Post Type
To link a custom editor stylesheet file based on the post type being edited, you can use the following in the functions.php file of your theme. This assumes the stylesheet files with names in the form of editor-style-{post_type}.css are present directly under your theme directory.
/** * Registers an editor stylesheet for the current theme. * * @global WP_Post $post Global post object. */ function wpdocs_theme_add_editor_styles() { global $post; $my_post_type = 'posttype'; // New post (init hook). if ( false !== stristr( $_SERVER['REQUEST_URI'], 'post-new.php' ) && ( isset( $_GET['post_type'] ) === true && $my_post_type == $_GET['post_type'] ) ) { add_editor_style( get_stylesheet_directory_uri() . '/css/editor-style-' . $my_post_type . '.css' ); } // Edit post (pre_get_posts hook). if ( stristr( $_SERVER['REQUEST_URI'], 'post.php' ) !== false && is_object( $post ) && $my_post_type == get_post_type( $post->ID ) ) { add_editor_style( get_stylesheet_directory_uri() . '/css/editor-style-' . $my_post_type . '.css' ); } } add_action( 'init', 'wpdocs_theme_add_editor_styles' ); add_action( 'pre_get_posts', 'wpdocs_theme_add_editor_styles' );Note that the pre_get_posts action hook is used to ensure that the post type is already determined but, at the same time, that TinyMCE has not been configured yet. That hook is not run when creating new posts, that is why we need to use it in combination with the init hook to achieve a consistent result.
Skip to note 18 content
BigupJeff
To add styles from a plugin use a URL in place of a path relative to the theme root.
// Will NOT work in plugin. add_editor_style( 'build/css/editor.css' ); // WILL work in plugin. add_editor_style( 'https://mywebsite.com/wp-content/plugins/myplugin/build/css/editor.css' );Skip to note 19 content
Brad Davis
If you are keeping your style files in a sub-directory, eg, css, you add the editor style with:
/** * Registers an editor stylesheet in a sub-directory. */ function add_editor_styles_sub_dir() { add_editor_style( trailingslashit( get_template_directory_uri() ) . 'css/editor-style.css' ); } add_action( 'after_setup_theme', 'add_editor_styles_sub_dir' );Skip to note 20 content
goulvench
Using Gutenberg, calling
add_theme_support( 'editor-styles' );is required before callingadd_editor_style(), even though the function is supposed to add theme support for editor styles.So if you want to add your own styles to the Gutenberg editor, be sure to call both functions:
add_action( 'admin_init', 'wpdocs_add_editor_styles' ); function wpdocs_add_editor_styles() { add_theme_support( 'editor-styles' ); add_editor_style( 'editor-style.css' ); }Skip to note 21 content
cweiser
Note that the Block Editor is unable to parse any file containing CSS @layers. Using CSS layers will prevent the entire file from being applied to the editor. Ex:
/* some-component.scss */ .wp-button__link { border: solid 1px green; } @layer theme { .wp-button__link { color: red !important; } } /* Neither of these styles will be applied due to usage of @layer */Skip to note 22 content
vee
If you have CSS that load font but not using full URL. For example:
all.css
@font-face {
src: url(../webfonts/fa-brands-400.woff2);
}
And then you use
add_editor_style([get_stylesheet_directory_uri() . '/css/all.css']). This CSS will not load font correctly and cause your font (from example is icon font by FontAwesome) not showing correctly.Skip to note 23 content
olik9
The example above can be rewritten simpler:
function value( $ar, $key, $default = '' ) { if ( is_array( $ar ) && isset( $ar[ $key ] ) ) { return $ar[ $key ]; } //else return $default; } /** * Registers an editor stylesheet for the current theme. * * @global WP_Post $post Global post object. */ function wpdocs_theme_add_editor_styles() { global $pagenow; global $post; $my_post_type = 'posttype'; if ( ( ( 'post-new.php' === $pagenow ) && ( value( $_GET, 'post_type' ) == $my_post_type ) ) || // New post (init hook) ( ( 'post.php' === $pagenow ) && is_object( $post ) && ( get_post_type( $post->ID ) == $my_post_type ) ) ) { // Edit post (pre_get_posts hook). add_editor_style( get_stylesheet_directory_uri() . '/css/editor-style-' . $my_post_type . '.css' ); } } add_action( 'admin_init', 'wpdocs_theme_add_editor_styles' ); add_action( 'pre_get_posts', 'wpdocs_theme_add_editor_styles' );Skip to note 24 content
Codex
Reusing Your Theme Styles
You can reuse the styles from your theme stylesheet file in your custom editor stylesheet file using the @import CSS rule. Working on the previous example, put the following instead into the custom-editor-style.css file.
@import url( 'style.css' ); /* Add overwrites as needed so that the content of the editor field is attractive and not broken */ body { padding: 0; background: #fff; }If necessary, change ‘style.css’ to the path to your theme stylesheet, relative to the custom-editor-style.css file.