如何在WordPress文章中调用自定义媒体字段自动显示为图片说明
完全可以实现无人工干预自动追加版权信息,我们通过WordPress原生钩子拦截图片渲染逻辑即可,不需要修改你现有的文章输出模板。
你可以将以下代码添加到当前主题的functions.php文件中:
// 自动为古腾堡图片块追加版权信息 add_filter('render_block', function ($block_content, $block) { // 仅处理图片类型区块 if ($block['blockName'] !== 'core/image') { return $block_content; } // 从img标签默认类名提取附件ID if (preg_match('/wp-image-(\d+)/', $block_content, $matches)) { $attachment_id = intval($matches[1]); // 获取你提前存储的版权自定义字段 $copyright = get_post_meta($attachment_id, 'media_copyright', true); if (!empty($copyright)) { // 构造版权栏HTML,自动插入到图片容器末尾 $copyright_html = '<div class="media-copyright">' . esc_html($copyright) . '</div>'; $block_content = str_replace('</figure>', $copyright_html . '</figure>', $block_content); } } return $block_content; }, 10, 2);
补充说明
- 以上代码仅对古腾堡编辑器插入的图片生效,如果你站点还有使用经典编辑器插入的历史图片,可以额外添加以下兼容代码:
// 兼容经典编辑器插入的图片 add_filter('the_content', function ($content) { if (is_singular(['post', 'page'])) { $content = preg_replace_callback('/<img[^>]+wp-image-(\d+)[^>]*>/i', function ($matches) { $attachment_id = intval($matches[1]); $copyright = get_post_meta($attachment_id, 'media_copyright', true); if (empty($copyright)) { return $matches[0]; } return $matches[0] . '<div class="media-copyright">' . esc_html($copyright) . '</div>'; }, $content); } return $content; }, 99);
- 你可以自行在主题CSS文件中添加
.media-copyright类的样式,调整版权栏的显示效果,示例样式参考:
.media-copyright { font-size: 12px; color: #666; text-align: right; padding: 4px 0; }
内容的提问来源于stack exchange,提问作者SelketDaly
相关产品推荐
相关产品推荐

