WordPress能不能后台编辑时候,最大可能和前台显示一致而不用一直“预览”?答案是可以的。追求的就是所见即所得。
要实现这个目的,大家一定要先了解,WordPress是有两大类后台编辑器,一类是经典编辑器。如下图:

还有一类是5.0新版之后缺省的区块编辑器:

这两种类型的后台编辑器添加自定义的CSS,方法是不一样的。首先,都是修改主题文件所在目录的functions.php,但修改代码略有不同。
经典编辑器需要追加的代码:
function somefunction(){
add_editor_style('editor-style.css');
}
add_action( 'after_setup_theme', 'somefunction' );
区块编辑器需要追加的代码:
add_theme_support('editor-styles');
add_editor_style('editor-style.css');
在基本追加代码之后,由于毕竟编辑器使用的HTML和实际前台显示的HTML还是不同的,需要我们自己精调editor-style.css,一般就是开两个窗口用F12里面选择元素定位之后查看各自的样式,然后修改。
值得注意的是前台主要内容“content”一般在后台编辑器中直接就是body了,改显示宽度就直接改body的吧。由于后台编辑器本身有缺省CSS,想自定义CSS的话,元素范围限定为类才能定位准确获得效果,比如前端CSS是h2 { font-size: 1.75em; },而后台编辑器CSS可能是h2.rich-text.block-editor-rich-text__editable { font-size: 1.75em; },记得多用F12。下面是举例我自己网站的一些简单自定义CSS:
hr.wp-block-separator {
border: 1px solid;
}
p.wp-block {
font-family: "Open Sans", Arial, sans-serif;
font-size: 17px;
line-height: 1.6;
color: #494949;
}
body {
width: 753px;
border: 1px solid LightGrey;
margin-left: auto;
margin-right: auto;
padding-left: 1.5625rem;
padding-right: 1.5625rem;
}
※参考文档: Getting the WordPress Block Editor to Look Like the Front End Design
–mkland.net原创