Remove duplicate featured images from blog content

- Add removeLeadingImage() to strip the first image from content when it matches
  the featured image, preventing duplication on blog post pages
- Handles figure wraps, linked images, and standalone img tags
- Featured image now appears only once (in the header), not repeated in content

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Jeff Emmett 2026-02-05 14:54:31 +00:00
parent 64da557836
commit da39ee7751
3 changed files with 100 additions and 68 deletions

View File

@ -195,6 +195,36 @@ function removeShortcodes(text) {
return clean; return clean;
} }
// Remove the first/leading image from content to avoid duplication with featured image
function removeLeadingImage(content, featuredImageUrl) {
if (!featuredImageUrl || !content) return content;
let result = content.trim();
// Pattern 1: Remove leading <figure class="wp-caption">...</figure> containing the featured image
const figureMatch = result.match(/^(\s*<figure[^>]*>[\s\S]*?<\/figure>\s*)/i);
if (figureMatch && figureMatch[1].includes(featuredImageUrl.split('?')[0])) {
result = result.substring(figureMatch[1].length).trim();
return result;
}
// Pattern 2: Remove leading <a><img></a> containing the featured image
const linkedImgMatch = result.match(/^(\s*<a[^>]*>[\s\S]*?<img[^>]*>[\s\S]*?<\/a>\s*)/i);
if (linkedImgMatch && linkedImgMatch[1].includes(featuredImageUrl.split('?')[0])) {
result = result.substring(linkedImgMatch[1].length).trim();
return result;
}
// Pattern 3: Remove leading standalone <img> containing the featured image
const imgMatch = result.match(/^(\s*<img[^>]*\/?>[\s*]*)/i);
if (imgMatch && imgMatch[1].includes(featuredImageUrl.split('?')[0])) {
result = result.substring(imgMatch[1].length).trim();
return result;
}
return result;
}
// Extract first paragraph as excerpt // Extract first paragraph as excerpt
function extractExcerpt(content, maxLength = 200) { function extractExcerpt(content, maxLength = 200) {
// First decode HTML entities in the raw content // First decode HTML entities in the raw content
@ -230,7 +260,9 @@ items.forEach((item, index) => {
const slug = createSlug(postName, title); const slug = createSlug(postName, title);
const images = extractImages(content); const images = extractImages(content);
const featuredImage = images[0] || null; const featuredImage = images[0] || null;
const cleanedContent = cleanContent(content); let cleanedContent = cleanContent(content);
// Remove the leading image from content if it matches the featured image (to avoid duplication)
cleanedContent = removeLeadingImage(cleanedContent, featuredImage);
const excerpt = extractExcerpt(cleanedContent); const excerpt = extractExcerpt(cleanedContent);
const data = { const data = {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long