如何为WordPress区块编辑器添加自定义宽高比(如21:9)
为WordPress区块编辑器添加自定义裁剪宽高比
实现方案
借助WordPress的钩子函数,在自定义主题的functions.php中编写代码,即可实现添加自定义宽高比、移除默认选项的需求,适配WordPress 6.2.2版本。
1. 修改裁剪工具的宽高比选项列表
在主题的functions.php中添加以下代码,可移除不需要的默认比例,同时加入21:9自定义比例:
function custom_image_aspect_ratios( $ratios ) { // 移除不需要的默认宽高比,比如示例中移除16:9 unset( $ratios['16:9'] ); // 添加21:9宽高比,第二个参数是显示名称,可替换为主题文本域支持翻译 $ratios['21:9'] = __( '21:9', 'your-theme-text-domain' ); // 如需添加其他比例,可继续扩展 // $ratios['4:3'] = __( '4:3', 'your-theme-text-domain' ); return $ratios; } add_filter( 'image_size_names_choose', 'custom_image_aspect_ratios' );
2. 为自定义比例配置裁剪规则
确保裁剪工具能正确识别并应用21:9比例,添加尺寸计算的钩子:
function custom_image_size_crop_settings( $sizes, $size, $image_meta ) { if ( '21:9' === $size ) { // 设置对应尺寸,比例保持21:9即可,数值可按需调整 $sizes['width'] = 2100; $sizes['height'] = 900; $sizes['crop'] = true; } return $sizes; } add_filter( 'wp_calculate_image_sizes', 'custom_image_size_crop_settings', 10, 3 );
3. 同步区块编辑器的比例选项
如果需要在图片区块的设置面板中也显示自定义比例,需添加JS扩展代码:
在主题目录下创建js/custom-image-ratios.js,写入以下内容:
wp.domReady( function() { // 移除编辑器中默认的16:9比例选项 wp.blockEditor.BlockControls.remove( 'core/image/aspect-ratio/16-9' ); // 添加21:9比例的控制按钮 wp.blockEditor.BlockControls.add( 'core/image/aspect-ratio/21-9', wp.element.createElement( wp.blockEditor.BlockControl, { icon: 'editor-align', label: '21:9', onClick: function() { const { select, dispatch } = wp.data; const selectedBlock = select( 'core/editor' ).getSelectedBlock(); if ( selectedBlock && selectedBlock.name === 'core/image' ) { dispatch( 'core/editor' ).updateBlockAttributes( selectedBlock.clientId, { width: 2100, height: 900, scale: 'cover' } ); } } } ) ); } );
再在functions.php中注册并加载这个JS文件:
function enqueue_custom_image_ratio_script() { if ( is_admin() ) { wp_enqueue_script( 'custom-image-ratios', get_template_directory_uri() . '/js/custom-image-ratios.js', array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-data' ), wp_get_theme()->get( 'Version' ), true ); } } add_action( 'admin_enqueue_scripts', 'enqueue_custom_image_ratio_script' );
注意事项
- 替换代码中的
your-theme-text-domain为你的主题实际文本域,用于多语言翻译支持。 - 自定义尺寸的宽高数值可按需调整,只要保持21:9的比例即可。
- 修改
functions.php前建议备份文件,避免代码错误导致网站异常。
内容的提问来源于stack exchange,提问作者fuchsmusstsein
相关产品推荐
相关产品推荐

