WordPress问题:已设置图片标题,Gutenberg无法自动读取
解决Gutenberg编辑器图片标题属性自动填充问题
Gutenberg默认不会将媒体库中图片的「标题」字段自动同步到图片块高级选项里的「标题属性」(对应前端img标签的title属性)。以下两种方法可实现通过图片post_id自动获取并填充该字段:
方法一:编辑器端实时自动填充(前端脚本)
通过自定义Gutenberg脚本,监听图片块的选择/加载事件,调用REST API获取媒体库中的图片标题,实时填充到标题属性字段。
1. 创建自定义JS脚本
在主题目录下新建js/gutenberg-image-title.js文件,写入以下代码:
wp.domReady( function() { // 监听编辑器块选择变化 wp.data.subscribe( function() { const selectedBlock = wp.data.select('core/editor').getSelectedBlock(); // 仅处理图片块,且标题属性为空时执行 if (selectedBlock?.name === 'core/image' && selectedBlock.attributes.id && !selectedBlock.attributes.title) { // 通过REST API获取媒体项详情 wp.apiFetch( { path: `/wp/v2/media/${selectedBlock.attributes.id}` } ) .then( media => { if (media.title?.rendered) { // 更新图片块的标题属性 wp.data.dispatch('core/editor').updateBlockAttributes( selectedBlock.clientId, { title: media.title.rendered } ); } } ); } } ); } );
2. 注册并加载脚本
在主题的functions.php中添加以下代码,将脚本加载到Gutenberg编辑器:
function enqueue_gutenberg_image_title_script() { if (is_admin()) { wp_enqueue_script( 'gutenberg-image-title-auto-fill', get_template_directory_uri() . '/js/gutenberg-image-title.js', array('wp-blocks', 'wp-editor', 'wp-data', 'wp-api-fetch'), wp_get_theme()->get('Version'), true ); } } add_action('enqueue_block_editor_assets', 'enqueue_gutenberg_image_title_script');
方法二:后端自动设置(保存文章时触发)
通过save_post钩子,在文章保存时自动遍历所有图片块,根据图片post_id获取媒体库标题并填充到标题属性,无需编辑器端操作。
在主题的functions.php中添加以下代码:
function auto_set_image_title_attribute($post_id) { // 跳过修订版本 if (wp_is_post_revision($post_id)) return; $post_content = get_post_field('post_content', $post_id); if (empty($post_content)) return; // 解析文章中的所有块 $blocks = parse_blocks($post_content); $updated_content = ''; foreach ($blocks as $block) { // 处理图片块,且标题属性为空的情况 if ($block['blockName'] === 'core/image' && isset($block['attrs']['id']) && empty($block['attrs']['title'])) { $media_id = $block['attrs']['id']; $media_title = get_the_title($media_id); if (!empty($media_title)) { $block['attrs']['title'] = $media_title; } } // 重新序列化块内容 $updated_content .= serialize_block($block); } // 仅在内容有变化时更新文章,避免无限循环 if ($updated_content !== $post_content) { remove_action('save_post', 'auto_set_image_title_attribute'); wp_update_post(array( 'ID' => $post_id, 'post_content' => $updated_content )); add_action('save_post', 'auto_set_image_title_attribute'); } } add_action('save_post', 'auto_set_image_title_attribute');
注意事项
- 方法一适合需要实时预览和手动调整的场景,方法二适合批量处理或强制统一设置的需求。
- 建议使用子主题添加代码,避免主题更新导致代码丢失;也可封装为独立插件使用。
- 确保WordPress REST API处于启用状态(默认启用),若网站有REST API权限限制,需调整对应设置。
内容的提问来源于stack exchange,提问作者Phạm Như Thái
相关产品推荐
相关产品推荐

