WordPress Gutenberg文章提取内嵌首图功能不稳定 寻求解决方案
问题根源
你原代码使用get_children()查询的是post_parent等于当前文章ID的图片附件,仅上传时直接上传到当前文章的图片才会匹配该条件。古腾堡编辑器默认插入媒体库已有图片时,不会修改附件的post_parent属性,所以新建文章插入的媒体库图片无法被这段代码捕获,$attachment为空后,后续调用的主题模板又加载了特色图,才会出现你观察到的异常现象。
修复方案
通过解析文章内容提取第一张图片,不受附件关联关系影响,完全兼容古腾堡区块:
- 先将下方工具函数添加到子主题的
functions.php文件中:
function get_post_first_image() { global $post; // 优先解析古腾堡核心图片区块 $post_blocks = parse_blocks($post->post_content); foreach ($post_blocks as $block) { if ($block['blockName'] === 'core/image' && isset($block['attrs']['id'])) { $img_url = wp_get_attachment_image_url($block['attrs']['id'], 'full'); if ($img_url) return $img_url; } } // 兼容旧文章/非区块编辑内容,正则匹配img标签 preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); if (isset($matches[1][0])) { return $matches[1][0]; } // 无匹配图片时可在此处返回自定义占位图地址,按需修改即可 return ''; }
- 替换你
archives.php中的原有代码,修改后完整逻辑如下:
<?php while ( have_posts() ) : ?> <?php the_post(); ?> <h2 class="archiveTitle" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2> <div class="archiveContainer"> <?php $first_img = get_post_first_image(); if( $first_img ) echo '<img src="' . esc_url($first_img) . '" class="post-attachment" />'; ?> </div> <?php get_template_part( 'template-parts/content/content', get_theme_mod( 'display_excerpt_or_full_post', 'excerpt' ) ); ?> <?php endwhile; ?>
可选优化
- 如需固定输出图片尺寸,可将
wp_get_attachment_image_url的第二个参数full修改为你需要的尺寸别名,比如medium、thumbnail或自定义尺寸,可降低页面加载耗时 - 如需过滤特定图片,可在遍历区块的逻辑中添加判断条件,比如排除带指定类名的图片
内容的提问来源于stack exchange,提问作者NPC
相关产品推荐
相关产品推荐

