如何无需使用子主题为Gutenberg编辑器添加自定义样式
古腾堡编辑器自定义样式实现方案(不用子主题、避免更新覆盖)
方案1:自建极简自定义插件(最推荐)
这个方案完全脱离主题目录,无论主题如何更新都不会影响自定义样式,同时解决了add_editor_style()无法跨目录加载文件的问题:
- 进入网站
wp-content/plugins/目录,新建独立文件夹,命名为custom-editor-styles - 在该文件夹内新建主文件
custom-editor-styles.php,写入基础插件声明:
<?php /* Plugin Name: 自定义古腾堡编辑器样式 Description: 同步编辑器与前端显示效果 Version: 1.0 */
- 将你的自定义样式文件重命名为
editor-style.css,存入该插件文件夹 - 在
custom-editor-styles.php末尾追加样式挂载代码:
// 加载自定义样式到古腾堡编辑器 function custom_gutenberg_editor_style() { wp_enqueue_style( 'custom-editor-css', plugins_url( 'editor-style.css', __FILE__ ), array( 'wp-edit-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'editor-style.css' ) ); } add_action( 'enqueue_block_editor_assets', 'custom_gutenberg_editor_style' ); // 可选:同步将同一份样式加载到前端,保证前后端效果完全一致 function custom_gutenberg_frontend_style() { wp_enqueue_style( 'custom-frontend-css', plugins_url( 'editor-style.css', __FILE__ ), array(), filemtime( plugin_dir_path( __FILE__ ) . 'editor-style.css' ) ); } add_action( 'wp_enqueue_scripts', 'custom_gutenberg_frontend_style' );
- 进入WordPress后台插件管理页,启用「自定义古腾堡编辑器样式」插件即可生效。
方案2:内联样式注入(无需新增独立样式文件)
如果不想创建插件,可以直接将样式代码注入到编辑器和前端,操作更轻量化:
- 将以下代码添加到当前主题的
functions.php文件末尾,后续主题更新前备份这段代码即可:
// 注入自定义样式到古腾堡编辑器 function custom_inline_editor_css() { $css = " /* 替换为你自己的样式规则 */ .wp-block-heading { font-weight: 600; margin-bottom: 20px; } .wp-block-paragraph { line-height: 1.7; color: #333; } "; wp_add_inline_style( 'wp-edit-blocks', $css ); } add_action( 'enqueue_block_editor_assets', 'custom_inline_editor_css' ); // 同步注入到前端 function custom_inline_frontend_css() { $css = " /* 和上面的样式规则保持一致 */ .wp-block-heading { font-weight: 600; margin-bottom: 20px; } .wp-block-paragraph { line-height: 1.7; color: #333; } "; wp_add_inline_style( 'wp-block-library', $css ); } add_action( 'wp_enqueue_scripts', 'custom_inline_frontend_css' );
内容的提问来源于stack exchange,提问作者GKaplan
相关产品推荐
相关产品推荐

