PluginProbe
Extendify / 3.1.0
Extendify v3.1.0
3.2.1 3.2.0 3.1.6 3.1.5 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 3.0.6 3.0.5 3.0.4 trunk 0.1.0 0.10.0 0.10.1 0.10.2 0.11.0 0.11.1 0.2.0 0.3.0 0.3.1 0.4.0 0.5.0 0.6.0 All 127 releases
extendify / src / Agent / workflows / content / tools / update-post-strings.js

update-post-strings.js in Extendify 3.1.0, at src/Agent/workflows/content/tools/update-post-strings.js

64 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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