如何为Gutenberg预览选项添加自定义设备类型/断点?
如何为Gutenberg编辑器添加自定义预览设备/断点并嵌入页眉区域
一、创建自定义预览设备与断点
要添加自定义预览设备,通过PHP过滤器修改编辑器的previewDevices配置,同时定义对应断点宽度即可:
- 在主题的
functions.php中添加以下代码:
add_filter( 'block_editor_settings_all', 'custom_gutenberg_preview_devices' ); function custom_gutenberg_preview_devices( $settings ) { // 自定义设备:平板竖屏(768px) $custom_device = array( 'name' => 'tablet-portrait', 'label' => '平板竖屏', 'width' => 768, 'icon' => 'tablet' // 可用WordPress内置图标名,比如laptop、mobile等 ); // 将自定义设备添加到默认设备列表末尾 $settings['previewDevices'][] = $custom_device; return $settings; }
这段代码会把自定义的平板竖屏设备加入编辑器预览设备选项,切换预览时会自动应用768px的断点宽度。
二、将自定义设备按钮添加到编辑器页眉中间区域
要把自定义设备切换按钮放到编辑器页眉中间区域,需要编写Gutenberg插件,利用PluginHeaderItem组件插入按钮:
- 在主题或插件中创建JS文件(比如
custom-preview-header.js),添加以下代码:
const { registerPlugin } = wp.plugins; const { PluginHeaderItem } = wp.editPost; const { Button } = wp.components; const { dispatch, select } = wp.data; const CustomPreviewButton = () => { const currentDevice = select('core/editor').getPreviewDeviceType(); return ( <PluginHeaderItem> <Button isTertiary isPressed={ currentDevice === 'tablet-portrait' } onClick={ () => dispatch('core/editor').setPreviewDeviceType('tablet-portrait') } icon="tablet" > 平板竖屏 </Button> </PluginHeaderItem> ); }; registerPlugin('custom-preview-header-button', { render: CustomPreviewButton, });
- 在
functions.php中注册并加载这个JS文件:
add_action( 'enqueue_block_editor_assets', 'enqueue_custom_preview_header_script' ); function enqueue_custom_preview_header_script() { wp_enqueue_script( 'custom-preview-header', get_template_directory_uri() . '/custom-preview-header.js', array( 'wp-plugins', 'wp-edit-post', 'wp-components', 'wp-data' ), wp_get_theme()->get('Version'), true ); }
这段代码会在编辑器页眉中间区域添加“平板竖屏”按钮,点击后直接切换到自定义预览模式,按钮激活状态会随当前预览设备自动切换。
注意事项
- 自定义设备的
name属性要唯一,不能和默认设备(比如desktop、tablet、mobile)重复; - 图标可以使用WordPress内置的Dashicons图标库中的图标名;
- 如需添加多个自定义设备,只需在PHP的
previewDevices数组中添加更多设备对象,同时在JS中对应添加多个PluginHeaderItem或用按钮组组件整合。
内容的提问来源于stack exchange,提问作者tomektomczuk
相关产品推荐
相关产品推荐

