| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
|
| 3 |
// TODO: check for post_lock and error that someone is editing |
| 4 |
export default async ({ postId, postType, replacements }) => { |
| 5 |
const type = postType === 'page' ? 'pages' : 'posts'; |
| 6 |
const response = await apiFetch({ |
| 7 |
path: `/wp/v2/${type}/${postId}?context=edit`, |
| 8 |
}); |
| 9 |
let content = response.content.raw; |
| 10 |
let title = response.title.raw; |
| 11 |
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 12 |
for (const { original, updated } of replacements) { |
| 13 |
const regex = new RegExp(escapeRegExp(original), 'g'); |
| 14 |
content = content.replace(regex, updated); |
| 15 |
title = title.split(original).join(updated); |
| 16 |
} |
| 17 |
|
| 18 |
const postResult = await apiFetch({ |
| 19 |
path: `/wp/v2/${type}/${postId}`, |
| 20 |
method: 'POST', |
| 21 |
data: { content, title }, |
| 22 |
}); |
| 23 |
|
| 24 |
// Also update any active template parts |
| 25 |
const slugs = [ |
| 26 |
...new Set( |
| 27 |
[...document.querySelectorAll('[data-extendify-part-slug]')].map( |
| 28 |
(el) => el.dataset.extendifyPartSlug, |
| 29 |
), |
| 30 |
), |
| 31 |
]; |
| 32 |
|
| 33 |
if (slugs.length > 0) { |
| 34 |
try { |
| 35 |
const allParts = await apiFetch({ |
| 36 |
path: '/wp/v2/template-parts?per_page=100&context=edit', |
| 37 |
}); |
| 38 |
const activeParts = allParts.filter((p) => slugs.includes(p.slug)); |
| 39 |
for (const part of activeParts) { |
| 40 |
let partContent = part.content.raw; |
| 41 |
let changed = false; |
| 42 |
for (const { original, updated } of replacements) { |
| 43 |
const regex = new RegExp(escapeRegExp(original), 'g'); |
| 44 |
if (regex.test(partContent)) { |
| 45 |
partContent = partContent.replace(regex, updated); |
| 46 |
changed = true; |
| 47 |
} |
| 48 |
} |
| 49 |
if (changed) { |
| 50 |
await apiFetch({ |
| 51 |
path: `/wp/v2/template-parts/${part.id}`, |
| 52 |
method: 'POST', |
| 53 |
data: { content: partContent }, |
| 54 |
}); |
| 55 |
} |
| 56 |
} |
| 57 |
} catch { |
| 58 |
// Template parts API may not be available, continue |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
return postResult; |
| 63 |
}; |
| 64 |
|