@forgewp/compiler 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +59 -0
  2. package/bin/add.js +20 -14
  3. package/bin/cli.js +145 -70
  4. package/bin/doctor.js +21 -12
  5. package/bin/export.js +69 -20
  6. package/bin/fresh.js +5 -0
  7. package/bin/i18n-extract.js +3 -10
  8. package/bin/i18n-translate.js +15 -24
  9. package/bin/make-block.js +13 -0
  10. package/bin/make-editable.js +166 -0
  11. package/bin/make-form.js +131 -0
  12. package/bin/make-loop.js +40 -43
  13. package/bin/make-mail.js +27 -0
  14. package/bin/make-post-type.js +57 -29
  15. package/bin/make-sandbox.js +62 -11
  16. package/bin/make-section.js +221 -0
  17. package/bin/make-shell.js +375 -0
  18. package/bin/repair.js +14 -26
  19. package/bin/seed.js +119 -0
  20. package/bin/sync-routes.js +107 -85
  21. package/lib/adapters/html-adapter.js +5 -0
  22. package/lib/adapters/stub-adapter.js +4 -0
  23. package/lib/add-component.js +153 -92
  24. package/lib/asset-loader.js +313 -3
  25. package/lib/assets/asset-graph.js +432 -0
  26. package/lib/assets/asset-pipeline.js +125 -0
  27. package/lib/assets/diagnostics-report.js +345 -0
  28. package/lib/assets/external-fetcher.js +173 -0
  29. package/lib/assets/font-orchestrator.js +348 -0
  30. package/lib/assets/font-usage-scanner.js +242 -0
  31. package/lib/assets/image-optimizer.js +229 -0
  32. package/lib/assets/index.js +51 -0
  33. package/lib/assets/preload-generator.js +70 -0
  34. package/lib/assets/public-url.js +153 -0
  35. package/lib/block-authoring-help.js +11 -0
  36. package/lib/blocks/ast-parser.js +67 -0
  37. package/lib/blocks/discover-blocks.js +146 -0
  38. package/lib/blocks/editor-scope.js +733 -0
  39. package/lib/blocks/editor-transpiler.js +1229 -0
  40. package/lib/blocks/index.js +2838 -0
  41. package/lib/blocks/php-transpiler.js +4928 -0
  42. package/lib/blocks/scanner.js +1487 -0
  43. package/lib/blocks/shared-utils.js +290 -0
  44. package/lib/blocks/source-sanitize.js +1449 -0
  45. package/lib/blueprints.js +31 -91
  46. package/lib/build-assets.js +38 -33
  47. package/lib/collect-page-template-routes.js +102 -0
  48. package/lib/collect-static-routes.js +175 -0
  49. package/lib/diagnostics.js +58 -33
  50. package/lib/export-theme.js +84 -5
  51. package/lib/extract-template-content.js +90 -0
  52. package/lib/forms-preview.js +42 -0
  53. package/lib/functions/cpt-routing.js +69 -0
  54. package/lib/functions/forms.js +2461 -0
  55. package/lib/functions/hydration-enqueuer.js +400 -0
  56. package/lib/functions/index.js +1623 -0
  57. package/lib/functions/load-menus.js +112 -0
  58. package/lib/functions/load-translations.js +148 -0
  59. package/lib/functions/rest-endpoints.js +2923 -0
  60. package/lib/functions/routing.js +765 -0
  61. package/lib/functions/seed-mock-data.js +392 -0
  62. package/lib/functions/seed-products.js +481 -0
  63. package/lib/functions/settings-page.js +273 -0
  64. package/lib/functions/theme-setup.js +494 -0
  65. package/lib/generate-theme.js +1916 -339
  66. package/lib/hydration/editable-schemas.js +332 -0
  67. package/lib/hydration/enter-hidden-initial.js +65 -0
  68. package/lib/hydration/form-schemas.js +227 -0
  69. package/lib/hydration/index.js +12 -0
  70. package/lib/hydration/is-interactive.js +951 -0
  71. package/lib/hydration/island-split.js +1231 -0
  72. package/lib/hydration/islands-scanner.js +599 -0
  73. package/lib/hydration/resolve-island-chunk.js +103 -0
  74. package/lib/hydration/resolve-island-component.js +52 -0
  75. package/lib/hydration/rollup-inputs.js +81 -0
  76. package/lib/hydration/root-class-extractor.js +220 -0
  77. package/lib/hydration/scan-app-providers.js +154 -0
  78. package/lib/hydration/static-lint.js +382 -0
  79. package/lib/hydration/transform.js +257 -0
  80. package/lib/hydration/uses-block-area.js +49 -0
  81. package/lib/hydration/utils.js +119 -0
  82. package/lib/i18n/translation-cache.js +141 -0
  83. package/lib/icon-registry.js +72 -0
  84. package/lib/index.d.ts +287 -8
  85. package/lib/index.js +2 -1
  86. package/lib/load-config.js +338 -242
  87. package/lib/mail-templates.js +37 -0
  88. package/lib/markup-processor.js +388 -102
  89. package/lib/node-runtime.js +7 -0
  90. package/lib/page-config-plugin.js +64 -20
  91. package/lib/php-builders.js +383 -44
  92. package/lib/react-adapter.js +983 -235
  93. package/lib/registration-metadata.js +11 -0
  94. package/lib/render-theme.mts +1410 -616
  95. package/lib/route-layout.js +76 -0
  96. package/lib/template-discovery.js +58 -0
  97. package/lib/theme-compatibility.js +32 -0
  98. package/lib/validate-export.js +2 -2
  99. package/lib/validate.js +27 -5
  100. package/lib/virtual-plugin.js +319 -0
  101. package/lib/walkthrough.md +26 -0
  102. package/package.json +16 -5
  103. package/templates/auth/cms/email-logs.json +9 -0
  104. package/templates/auth/cms/menus.json +11 -0
  105. package/templates/auth/cms/mock-data.json +123 -0
  106. package/templates/auth/cms/roles.json +7 -0
  107. package/templates/auth/cms/sessions.json +1 -0
  108. package/templates/auth/cms/site-settings.json +28 -0
  109. package/templates/auth/cms/translations.json +4 -0
  110. package/templates/auth/cms/users.json +46 -0
  111. package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
  112. package/templates/auth/components/login-form-wrapper.tsx +118 -21
  113. package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
  114. package/templates/auth/components/signup-form-wrapper.tsx +2 -2
  115. package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
  116. package/templates/auth/pages/DashboardPage.tsx +1 -4
  117. package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
  118. package/templates/auth/pages/LoginPage.tsx +1 -4
  119. package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
  120. package/templates/auth/pages/SignUpPage.tsx +1 -4
  121. package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
  122. package/templates/auth/ui/button.tsx +57 -0
  123. package/templates/auth/ui/card.tsx +76 -0
  124. package/templates/auth/ui/field.tsx +242 -0
  125. package/templates/auth/ui/input.tsx +22 -0
  126. package/templates/auth/ui/label.tsx +24 -0
  127. package/templates/auth/ui/separator.tsx +31 -0
  128. package/templates/menus.json +12 -10
  129. package/templates/users.json +8 -4
  130. package/templates/wordpress.tsx +690 -245
  131. package/lib/block-compiler.js +0 -552
  132. package/lib/functions-builder.js +0 -2970
  133. package/lib/hydration-scanner.js +0 -833
@@ -0,0 +1,1623 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { buildThemeSetupPhp } from './theme-setup.js';
4
+ import { buildRoutingPhp } from './routing.js';
5
+ import { buildHydrationEnqueuerPhp } from './hydration-enqueuer.js';
6
+ import { buildRestEndpointsPhp } from './rest-endpoints.js';
7
+ import { buildSettingsPagePhp } from './settings-page.js';
8
+ import { buildFormsPhp } from './forms.js';
9
+ import { buildSeedProductsPhp } from './seed-products.js';
10
+ import { buildSeedMockDataPhp, loadMockData } from './seed-mock-data.js';
11
+ import { scanAppProviders } from '../hydration/scan-app-providers.js';
12
+ import { collectCptRouteDiagnostics, buildCptRewriteRefreshPhp } from './cpt-routing.js';
13
+
14
+ export function buildFunctionsPhp(
15
+ config,
16
+ assets,
17
+ blockSlugs = [],
18
+ themeRoot = '',
19
+ pagesToAutoCreate = [],
20
+ menus = {},
21
+ hydrationData = null,
22
+ i18nKeys = [],
23
+ schemas = {},
24
+ queries = [],
25
+ wpOptions = [],
26
+ ) {
27
+ let hasAuth = Boolean(
28
+ config.auth || (config.features && config.features.auth),
29
+ );
30
+
31
+ const rootsToInspect = [themeRoot, process.cwd()].filter(Boolean);
32
+ for (const root of rootsToInspect) {
33
+ try {
34
+ const packageJsonPath = path.join(root, 'package.json');
35
+ if (existsSync(packageJsonPath)) {
36
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
37
+ if (
38
+ (pkg.dependencies && pkg.dependencies['@forgewp/auth']) ||
39
+ (pkg.devDependencies && pkg.devDependencies['@forgewp/auth']) ||
40
+ (pkg.peerDependencies && pkg.peerDependencies['@forgewp/auth'])
41
+ ) {
42
+ hasAuth = true;
43
+ break;
44
+ }
45
+ }
46
+ } catch (e) {}
47
+ }
48
+
49
+ const defaultLoginField = config.auth?.loginField || 'usernameAndEmail';
50
+ const defaultRegistrationEnabled =
51
+ config.auth?.features?.registration !== false ? '1' : '0';
52
+ const defaultEmailVerificationEnabled =
53
+ config.auth?.features?.emailVerification === true ? '1' : '0';
54
+ const defaultBlockLoginUntilVerified =
55
+ config.auth?.features?.blockLoginUntilVerified === true ? '1' : '0';
56
+ const defaultAutoLoginAfterSignup =
57
+ config.auth?.features?.autoLoginAfterSignup !== false ? '1' : '0';
58
+ const defaultDefaultRole = config.auth?.defaultRole || 'subscriber';
59
+ const defaultVerificationEmailSubject =
60
+ config.auth?.emails?.verification?.subject || 'Please Verify Your Email';
61
+ const defaultVerificationEmailBody =
62
+ config.auth?.emails?.verification?.body ||
63
+ 'Please click the link below to verify your email address:\n\n{verification_url}';
64
+ const defaultPasswordResetEmailSubject =
65
+ config.auth?.emails?.passwordReset?.subject || 'Password Reset Request';
66
+ const defaultPasswordResetEmailBody =
67
+ config.auth?.emails?.passwordReset?.body ||
68
+ 'Click this link to reset your password:\n\n{reset_url}';
69
+
70
+ const reservedUsernames = config.auth?.reservedUsernames || [
71
+ 'admin',
72
+ 'system',
73
+ 'root',
74
+ ];
75
+ const reservedUsernamesPhp = reservedUsernames
76
+ .map((u) => `'${u.toLowerCase().replace(/'/g, "\\'")}'`)
77
+ .join(', ');
78
+
79
+ let currentUserHydrationField = '';
80
+ if (hasAuth) {
81
+ currentUserHydrationField =
82
+ "\n 'currentUser' => forgewp_get_current_user_hydration_payload(),";
83
+ }
84
+
85
+ const css = assets.cssFile.replace(/^assets\//, '');
86
+
87
+ // Schema-graph integration is gated on actual plugin presence at runtime
88
+ // (defined('WPSEO_VERSION') / class_exists('RankMath')), not a separate
89
+ // wp.config.ts flag — a manual opt-in flag can silently drift out of sync
90
+ // with whichever plugin is actually installed, which previously meant a
91
+ // developer could have Yoast active and forget to also set
92
+ // config.seo.plugins.yoast, causing ForgeWP's schema to silently never
93
+ // reach Yoast's graph. Emitting both integrations unconditionally (each
94
+ // wrapped in its own presence check) makes this automatic instead.
95
+ let seoPluginsPhp = `
96
+ /**
97
+ * Automatically integrate ForgeWP enqueued schemas with Yoast SEO Schema Graph.
98
+ */
99
+ if (defined('WPSEO_VERSION')) {
100
+ add_filter('wpseo_schema_graph', function($graph) {
101
+ $target = forgewp_resolve_head_target();
102
+ if (file_exists($target)) {
103
+ ob_start();
104
+ include $target;
105
+ $content = ob_get_clean();
106
+ if (preg_match_all('/<script type="application\\/ld\\+json">(.*?)<\\/script>/is', $content, $matches)) {
107
+ foreach ($matches[1] as $json_str) {
108
+ $decoded = json_decode(trim($json_str), true);
109
+ if (is_array($decoded) && is_array($graph)) {
110
+ $graph[] = $decoded;
111
+ }
112
+ }
113
+ }
114
+ }
115
+ return $graph;
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Automatically integrate ForgeWP enqueued schemas with RankMath JSON-LD.
121
+ */
122
+ if (class_exists('RankMath')) {
123
+ add_filter('rank_math/json_ld', function($data, $jsonld) {
124
+ $target = forgewp_resolve_head_target();
125
+ if (file_exists($target)) {
126
+ ob_start();
127
+ include $target;
128
+ $content = ob_get_clean();
129
+ if (preg_match_all('/<script type="application\\/ld\\+json">(.*?)<\\/script>/is', $content, $matches)) {
130
+ foreach ($matches[1] as $json_str) {
131
+ $decoded = json_decode(trim($json_str), true);
132
+ if (is_array($decoded) && is_array($data)) {
133
+ $data[] = $decoded;
134
+ }
135
+ }
136
+ }
137
+ }
138
+ return $data;
139
+ }, 99, 2);
140
+ }
141
+ `;
142
+
143
+ // Discover social media options dynamically from config.options
144
+ let socialKeys = [
145
+ 'facebook',
146
+ 'instagram',
147
+ 'twitter',
148
+ 'youtube',
149
+ 'tiktok',
150
+ 'linkedin',
151
+ 'pinterest',
152
+ ]; // default fallbacks
153
+ if (config.options && typeof config.options === 'object') {
154
+ const optionsKeys = Object.keys(config.options);
155
+ const discoveredSocials = optionsKeys
156
+ .filter((k) => k.startsWith('social_'))
157
+ .map((k) => k.replace(/^social_/, ''));
158
+ if (discoveredSocials.length > 0) {
159
+ socialKeys = Array.from(new Set([...socialKeys, ...discoveredSocials]));
160
+ }
161
+ }
162
+
163
+ let socialSettingsPhp = '';
164
+ for (const key of socialKeys) {
165
+ const optionName = `social_${key}`;
166
+ const capitalizedLabel = key
167
+ .split('_')
168
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
169
+ .join(' ');
170
+ socialSettingsPhp += `
171
+ // ${optionName}
172
+ $wp_customize->add_setting(
173
+ '${optionName}',
174
+ array(
175
+ 'type' => 'option',
176
+ 'default' => '',
177
+ 'sanitize_callback' => 'esc_url_raw',
178
+ )
179
+ );
180
+ $wp_customize->add_control(
181
+ '${optionName}',
182
+ array(
183
+ 'label' => __('${capitalizedLabel} URL', '${config.textDomain}'),
184
+ 'section' => 'forgewp_social_section',
185
+ 'type' => 'url',
186
+ )
187
+ );`;
188
+ }
189
+
190
+ const uniqueMetaKeys = new Set();
191
+ const metaKeyTypes = {};
192
+ const metaKeysToSkip = new Set();
193
+
194
+ for (const [templateSlug, schema] of Object.entries(schemas)) {
195
+ for (const [key, field] of Object.entries(schema)) {
196
+ uniqueMetaKeys.add(key);
197
+ const typeMap = {
198
+ text: 'string',
199
+ richText: 'string',
200
+ image: 'string',
201
+ boolean: 'boolean',
202
+ repeater: 'string',
203
+ };
204
+ metaKeyTypes[key] = typeMap[field.type] || 'string';
205
+ if (
206
+ field.skipRegisterMeta === true ||
207
+ field.customType === 'relationship'
208
+ ) {
209
+ metaKeysToSkip.add(key);
210
+ }
211
+ }
212
+ }
213
+
214
+ const uniqueRichTextKeys = [];
215
+ for (const [templateSlug, schema] of Object.entries(schemas)) {
216
+ for (const [key, field] of Object.entries(schema)) {
217
+ if (field.type === 'richText' && !uniqueRichTextKeys.includes(key)) {
218
+ uniqueRichTextKeys.push(key);
219
+ }
220
+ }
221
+ }
222
+
223
+ let postTypes = [];
224
+ let registeredTaxonomies = [];
225
+ const polylangMetaStrings = [];
226
+ for (const [templateSlug, schema] of Object.entries(schemas)) {
227
+ for (const [key, field] of Object.entries(schema)) {
228
+ if (
229
+ (field.type === 'text' || field.type === 'richText') &&
230
+ field.default
231
+ ) {
232
+ polylangMetaStrings.push(field.default);
233
+ }
234
+ }
235
+ }
236
+
237
+ const uniquePolylangStrings = Array.from(
238
+ new Set([...i18nKeys, ...polylangMetaStrings]),
239
+ );
240
+
241
+ const i18nKeysPhp = uniquePolylangStrings
242
+ .map((k) => ` '${k.replace(/'/g, "\\'")}',`)
243
+ .join('\n');
244
+ let cptRegistration = '';
245
+ try {
246
+ const cmsDir = path.join(themeRoot, 'cms');
247
+ let mockData = { ...loadMockData(themeRoot) };
248
+ if (existsSync(cmsDir)) {
249
+ const skipJson = new Set([
250
+ 'menus.json',
251
+ 'users.json',
252
+ 'roles.json',
253
+ 'sessions.json',
254
+ 'translations.json',
255
+ 'mock-data.json',
256
+ ]);
257
+ const jsonFiles = readdirSync(cmsDir).filter(
258
+ (f) => f.endsWith('.json') && !skipJson.has(f),
259
+ );
260
+ for (const f of jsonFiles) {
261
+ try {
262
+ const fileContent = JSON.parse(
263
+ readFileSync(path.join(cmsDir, f), 'utf8'),
264
+ );
265
+ if (
266
+ fileContent &&
267
+ typeof fileContent === 'object' &&
268
+ !Array.isArray(fileContent)
269
+ ) {
270
+ mockData = { ...mockData, ...fileContent };
271
+ }
272
+ } catch {}
273
+ }
274
+ }
275
+ if (config.postTypes && typeof config.postTypes === 'object') {
276
+ for (const pt of Object.keys(config.postTypes)) {
277
+ if (!mockData[pt]) mockData[pt] = [];
278
+ }
279
+ }
280
+
281
+ if (Object.keys(mockData).length > 0) {
282
+ postTypes = Object.keys(mockData).filter(
283
+ (k) =>
284
+ k !== 'posts' &&
285
+ k !== 'pages' &&
286
+ k !== 'post' &&
287
+ k !== 'page' &&
288
+ k !== 'menus' &&
289
+ k !== 'attachment' &&
290
+ !k.startsWith('_'),
291
+ );
292
+ if (postTypes.length > 0) {
293
+ const taxonomiesSet = new Set();
294
+ const postTypeTaxonomies = {};
295
+ const postTypeNativeTaxonomies = {};
296
+
297
+ for (const pt of postTypes) {
298
+ if (pt.length > 20) {
299
+ throw new Error(
300
+ `Custom Post Type "${pt}" inferred from local mock data exceeds the WordPress limit of 20 characters. Please shorten the key.`,
301
+ );
302
+ }
303
+ postTypeTaxonomies[pt] = new Set();
304
+ postTypeNativeTaxonomies[pt] = new Set();
305
+ const items = mockData[pt];
306
+ if (Array.isArray(items)) {
307
+ for (const item of items) {
308
+ if (item._terms && typeof item._terms === 'object') {
309
+ for (const tax of Object.keys(item._terms)) {
310
+ if (tax !== 'category' && tax !== 'post_tag') {
311
+ taxonomiesSet.add(tax);
312
+ postTypeTaxonomies[pt].add(tax);
313
+ } else {
314
+ postTypeNativeTaxonomies[pt].add(tax);
315
+ }
316
+ }
317
+ }
318
+ }
319
+ }
320
+ }
321
+
322
+ registeredTaxonomies = Array.from(taxonomiesSet);
323
+
324
+ function formatSingularLabel(slug) {
325
+ if (!slug) return '';
326
+ const words = slug
327
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
328
+ .split(/[_\-\s]+/)
329
+ .filter(Boolean);
330
+
331
+ const formatted = words.map((w) => {
332
+ const lower = w.toLowerCase();
333
+ if (lower === 'cat' || lower === 'cats') return 'Category';
334
+ if (lower === 'tag' || lower === 'tags') return 'Tag';
335
+ return w.charAt(0).toUpperCase() + w.slice(1);
336
+ });
337
+
338
+ return formatted.join(' ');
339
+ }
340
+
341
+ function pluralizeLabel(singularStr) {
342
+ if (!singularStr) return '';
343
+ const words = singularStr.trim().split(/\s+/);
344
+ const lastWord = words[words.length - 1];
345
+ const lastLower = lastWord.toLowerCase();
346
+
347
+ let pluralLast = lastWord;
348
+
349
+ if (lastLower.endsWith('y') && !/[aeiou]y$/i.test(lastLower)) {
350
+ pluralLast =
351
+ lastWord.slice(0, -1) +
352
+ (lastWord.charAt(lastWord.length - 1) === 'Y' ? 'IES' : 'ies');
353
+ } else if (/(?:s|x|z|ch|sh|ss)$/i.test(lastLower)) {
354
+ pluralLast =
355
+ lastWord +
356
+ (lastWord.charAt(lastWord.length - 1) ===
357
+ lastWord.charAt(lastWord.length - 1).toUpperCase() &&
358
+ lastWord.length > 1
359
+ ? 'ES'
360
+ : 'es');
361
+ } else if (/(?:fe)$/i.test(lastLower)) {
362
+ pluralLast = lastWord.slice(0, -2) + 'ves';
363
+ } else if (/(?:[^f]f)$/i.test(lastLower)) {
364
+ pluralLast = lastWord.slice(0, -1) + 'ves';
365
+ } else if (!lastLower.endsWith('s')) {
366
+ pluralLast = lastWord + 's';
367
+ }
368
+
369
+ words[words.length - 1] = pluralLast;
370
+ return words.join(' ');
371
+ }
372
+
373
+ cptRegistration = `
374
+ /**
375
+ * Register dynamic Custom Post Types inferred from local mock data.
376
+ */
377
+ function forgewp_register_custom_post_types() {
378
+ ${postTypes
379
+ .map((pt) => {
380
+ const ptConfig = config.postTypes?.[pt];
381
+ const singular = ptConfig?.labels?.singular || formatSingularLabel(pt);
382
+ const plural = ptConfig?.labels?.plural || pluralizeLabel(singular);
383
+ const icon = ptConfig?.icon || 'dashicons-admin-post';
384
+ const hasArchive = ptConfig?.hasArchive === false ? 'false' : 'true';
385
+ const supports = ptConfig?.supports ?? ['title', 'editor', 'thumbnail', 'custom-fields', 'excerpt'];
386
+ // An empty array makes WordPress add its default features. false is the
387
+ // native sentinel required to honor an explicitly empty feature list.
388
+ const supportsPhp = supports.length === 0 ? 'false' : `array(${supports.map((feature) => `'${String(feature).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`).join(', ')})`;
389
+ const rewriteSlug =
390
+ ptConfig?.rewrite && typeof ptConfig.rewrite === 'object'
391
+ ? String(ptConfig.rewrite.slug || pt)
392
+ .replace(/\\/g, '\\\\')
393
+ .replace(/'/g, "\\'")
394
+ : pt;
395
+ const rewrite =
396
+ ptConfig?.rewrite === false
397
+ ? 'false'
398
+ : ptConfig?.rewrite && typeof ptConfig.rewrite === 'object'
399
+ ? `array('slug' => '${rewriteSlug}', 'with_front' => ${ptConfig.rewrite.withFront === false ? 'false' : 'true'})`
400
+ : 'true';
401
+
402
+ const nativeTaxes = Array.from(postTypeNativeTaxonomies[pt] || []);
403
+ const taxonomiesLine =
404
+ nativeTaxes.length > 0
405
+ ? `\n 'taxonomies' => array('${nativeTaxes.join("', '")}'),`
406
+ : '';
407
+ const nativeTaxesCalls = nativeTaxes
408
+ .map(
409
+ (tax) => `\n register_taxonomy_for_object_type('${tax}', '${pt}');`,
410
+ )
411
+ .join('');
412
+ return ` if ( ! post_type_exists('${pt}') ) {
413
+ register_post_type('${pt}', array(
414
+ 'labels' => array(
415
+ 'name' => __('${plural}', '${config.textDomain}'),
416
+ 'singular_name' => __('${singular}', '${config.textDomain}'),
417
+ 'menu_name' => __('${plural}', '${config.textDomain}'),
418
+ 'name_admin_bar' => __('${singular}', '${config.textDomain}'),
419
+ 'add_new' => __('Add New', '${config.textDomain}'),
420
+ 'add_new_item' => __('Add New ${singular}', '${config.textDomain}'),
421
+ 'new_item' => __('New ${singular}', '${config.textDomain}'),
422
+ 'edit_item' => __('Edit ${singular}', '${config.textDomain}'),
423
+ 'view_item' => __('View ${singular}', '${config.textDomain}'),
424
+ 'all_items' => __('All ${plural}', '${config.textDomain}'),
425
+ 'search_items' => __('Search ${plural}', '${config.textDomain}'),
426
+ 'not_found' => __('No ${plural} found.', '${config.textDomain}'),
427
+ ),
428
+ 'public' => ${ptConfig?.public === false ? 'false' : 'true'},
429
+ 'has_archive' => ${hasArchive},
430
+ 'rewrite' => ${rewrite},
431
+ 'show_in_rest'=> ${ptConfig?.showInRest === false ? 'false' : 'true'},${taxonomiesLine}
432
+ 'supports' => ${supportsPhp},
433
+ 'menu_icon' => '${icon}',
434
+ ));${nativeTaxesCalls}
435
+ }`;
436
+ })
437
+ .join('\n')}
438
+
439
+ ${registeredTaxonomies
440
+ .map((tax) => {
441
+ const associatedPostTypes = postTypes.filter((pt) =>
442
+ postTypeTaxonomies[pt].has(tax),
443
+ );
444
+ const taxConfig = config.taxonomies?.[tax];
445
+ const singular = taxConfig?.labels?.singular || formatSingularLabel(tax);
446
+ const plural = taxConfig?.labels?.plural || pluralizeLabel(singular);
447
+ const hierarchical =
448
+ taxConfig?.hierarchical !== undefined
449
+ ? Boolean(taxConfig.hierarchical)
450
+ : true;
451
+ return ` if ( ! taxonomy_exists('${tax}') ) {
452
+ register_taxonomy('${tax}', array('${associatedPostTypes.join("', '")}'), array(
453
+ 'labels' => array(
454
+ 'name' => '${plural}',
455
+ 'singular_name' => '${singular}',
456
+ 'search_items' => 'Search ${plural}',
457
+ 'all_items' => 'All ${plural}',
458
+ 'parent_item' => 'Parent ${singular}',
459
+ 'parent_item_colon' => 'Parent ${singular}:',
460
+ 'edit_item' => 'Edit ${singular}',
461
+ 'update_item' => 'Update ${singular}',
462
+ 'add_new_item' => 'Add New ${singular}',
463
+ 'new_item_name' => 'New ${singular} Name',
464
+ 'menu_name' => '${plural}',
465
+ ),
466
+ 'hierarchical' => ${hierarchical ? 'true' : 'false'},
467
+ 'public' => ${taxConfig?.public === false ? 'false' : 'true'},
468
+ 'show_ui' => ${taxConfig?.showUi === false ? 'false' : 'true'},
469
+ 'show_admin_column' => true,
470
+ 'query_var' => true,
471
+ 'show_in_rest' => ${taxConfig?.showInRest === false ? 'false' : 'true'},
472
+ ));
473
+ }`;
474
+ })
475
+ .join('\n\n')}
476
+ }
477
+ add_action('init', 'forgewp_register_custom_post_types');
478
+ ${(() => {
479
+ const translatablePtKeys = Object.entries(config.postTypes || {})
480
+ .filter(([_, ptc]) => ptc.translatable)
481
+ .map(([key]) => key);
482
+ let php =
483
+ translatablePtKeys.length > 0
484
+ ? `\n// Automatically register custom post types for Polylang translation support
485
+ add_filter('pll_get_post_types', function($post_types, $is_settings) {
486
+ ${translatablePtKeys.map((pt) => ` $post_types['${pt}'] = '${pt}';`).join('\n')}
487
+ return $post_types;
488
+ }, 10, 2);`
489
+ : '';
490
+
491
+ if (translatablePtKeys.length > 0) {
492
+ php += `\n\n// Add REST API language filtering support for custom post types under Polylang
493
+ function forgewp_rest_query_language_filter($args, $request) {
494
+ $lang = $request->get_param('lang');
495
+ if (!empty($lang)) {
496
+ $args['lang'] = sanitize_text_field($lang);
497
+ } elseif (function_exists('pll_current_language')) {
498
+ $args['lang'] = pll_current_language();
499
+ }
500
+ return $args;
501
+ }
502
+ `;
503
+ translatablePtKeys.forEach((pt) => {
504
+ php += `add_filter('rest_${pt}_query', 'forgewp_rest_query_language_filter', 10, 2);\n`;
505
+ });
506
+ }
507
+
508
+ if (registeredTaxonomies.length > 0) {
509
+ php += `\n\n// Automatically register custom taxonomies for Polylang translation support
510
+ add_filter('pll_get_taxonomies', function($taxonomies, $is_settings) {
511
+ ${registeredTaxonomies.map((tax) => ` $taxonomies['${tax}'] = '${tax}';`).join('\n')}
512
+ return $taxonomies;
513
+ }, 10, 2);`;
514
+
515
+ const taxArrayStr = registeredTaxonomies
516
+ .map((tax) => `'${tax}'`)
517
+ .join(', ');
518
+ php += `\n\n// Automatically expose custom taxonomy metadata in WordPress REST API
519
+ add_action('rest_api_init', function() {
520
+ $taxonomies = array(${taxArrayStr});
521
+ foreach ($taxonomies as $tax) {
522
+ register_rest_field($tax, 'meta', array(
523
+ 'get_callback' => function($term) use ($tax) {
524
+ $term_id = $term['id'];
525
+
526
+ // Retrieve values using ACF if available, or direct term meta as fallback
527
+ $featured_image = function_exists('get_field') ? get_field('featured_image', 'term_' . $term_id) : null;
528
+ $flag = function_exists('get_field') ? get_field('flag', 'term_' . $term_id) : null;
529
+
530
+ if (empty($featured_image)) {
531
+ $featured_image = get_term_meta($term_id, 'featured_image', true);
532
+ }
533
+ if (empty($flag)) {
534
+ $flag = get_term_meta($term_id, 'flag', true);
535
+ }
536
+
537
+ return array(
538
+ 'featured_image' => !empty($featured_image) ? $featured_image : '',
539
+ 'flag' => !empty($flag) ? $flag : ''
540
+ );
541
+ },
542
+ 'update_callback' => null,
543
+ 'schema' => null,
544
+ ));
545
+ }
546
+ });`;
547
+ }
548
+
549
+ if (translatablePtKeys.length > 0 || registeredTaxonomies.length > 0) {
550
+ const ptArrayStr = translatablePtKeys.map((pt) => `'${pt}'`).join(', ');
551
+ const taxArrayStr = registeredTaxonomies
552
+ .map((tax) => `'${tax}'`)
553
+ .join(', ');
554
+ php += `\n\n// Automatically enable Polylang translation support for custom post types and taxonomies in WP Admin settings
555
+ add_action('admin_init', function() {
556
+ $options = get_option('polylang');
557
+ if (is_array($options)) {
558
+ $modified = false;
559
+
560
+ $cpts_to_enable = array(${ptArrayStr});
561
+ if (!isset($options['post_types'])) {
562
+ $options['post_types'] = array();
563
+ }
564
+ foreach ($cpts_to_enable as $cpt) {
565
+ if (!in_array($cpt, $options['post_types'])) {
566
+ $options['post_types'][] = $cpt;
567
+ $modified = true;
568
+ }
569
+ }
570
+
571
+ $taxonomies_to_enable = array(${taxArrayStr});
572
+ if (!isset($options['taxonomies'])) {
573
+ $options['taxonomies'] = array();
574
+ }
575
+ foreach ($taxonomies_to_enable as $tax) {
576
+ if (!in_array($tax, $options['taxonomies'])) {
577
+ $options['taxonomies'][] = $tax;
578
+ $modified = true;
579
+ }
580
+ }
581
+
582
+ if ($modified) {
583
+ update_option('polylang', $options);
584
+ flush_rewrite_rules();
585
+ }
586
+ }
587
+ });
588
+
589
+ // Automatically filter out Polylang internal hidden taxonomies from relationship fields to prevent empty selections and '0' labels
590
+ add_filter('get_object_taxonomies', function($taxonomies, $object, $output) {
591
+ if (is_admin() && is_array($taxonomies)) {
592
+ foreach ($taxonomies as $key => $tax) {
593
+ $tax_name = is_object($tax) ? $tax->name : $tax;
594
+ if ($tax_name === 'post_translations' || $tax_name === 'term_translations' || strpos($tax_name, 'pll_') === 0) {
595
+ unset($taxonomies[$key]);
596
+ }
597
+ }
598
+ if ($output !== 'objects') {
599
+ $taxonomies = array_values($taxonomies);
600
+ }
601
+ }
602
+ return $taxonomies;
603
+ }, 99, 3);`;
604
+ }
605
+ return php;
606
+ })()}
607
+ `;
608
+ }
609
+ }
610
+ } catch (e) {}
611
+
612
+ let fontsEnqueue = '';
613
+ let preconnectFilter = '';
614
+
615
+ const googleFonts = config.settings?.typography?.googleFonts || [];
616
+ if (googleFonts.length > 0) {
617
+ const fontsParam = googleFonts
618
+ .map((f) => encodeURIComponent(f))
619
+ .join('&family=');
620
+ fontsEnqueue = `
621
+ // Enqueue Google Fonts (dynamic preset via wp.config.ts)
622
+ wp_enqueue_style(
623
+ '${config.textDomain}-google-fonts',
624
+ 'https://fonts.googleapis.com/css2?family=${fontsParam}&display=swap',
625
+ array(),
626
+ null
627
+ );`;
628
+
629
+ preconnectFilter = `
630
+ /**
631
+ * Add preconnect resource hints for Google Fonts performance.
632
+ */
633
+ function forgewp_google_fonts_resource_hints(array $urls, string $relation_type): array {
634
+ if (wp_style_is('${config.textDomain}-google-fonts', 'queue') && 'preconnect' === $relation_type) {
635
+ $urls[] = array(
636
+ 'href' => 'https://fonts.googleapis.com',
637
+ 'crossorigin' => 'anonymous',
638
+ );
639
+ $urls[] = array(
640
+ 'href' => 'https://fonts.gstatic.com',
641
+ 'crossorigin' => 'anonymous',
642
+ );
643
+ }
644
+ return $urls;
645
+ }
646
+ add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
647
+ `;
648
+ }
649
+
650
+ let blocksRegistration = '';
651
+ if (blockSlugs.length > 0) {
652
+ const customCategories = [];
653
+ const seenCategories = new Set();
654
+ for (const block of blockSlugs) {
655
+ if (block.category && block.category.startsWith('forgewp-')) {
656
+ const slug = block.category;
657
+ if (!seenCategories.has(slug)) {
658
+ seenCategories.add(slug);
659
+ const rawName = slug.replace('forgewp-', '');
660
+ const title =
661
+ 'ForgeWP ' + rawName.charAt(0).toUpperCase() + rawName.slice(1);
662
+ customCategories.push({ slug, title });
663
+ }
664
+ }
665
+ }
666
+
667
+ let categoriesHook = '';
668
+ if (customCategories.length > 0) {
669
+ const categoriesPhpArray = customCategories
670
+ .map(
671
+ (c) =>
672
+ ` array('slug' => '${c.slug}', 'title' => '${c.title}')`,
673
+ )
674
+ .join(',\n');
675
+
676
+ categoriesHook = `
677
+ /**
678
+ * Register custom block categories for ForgeWP.
679
+ */
680
+ function forgewp_register_custom_block_categories($categories): array {
681
+ return array_merge(
682
+ $categories,
683
+ array(
684
+ ${categoriesPhpArray}
685
+ )
686
+ );
687
+ }
688
+ add_filter('block_categories_all', 'forgewp_register_custom_block_categories', 10, 2);
689
+ `;
690
+ }
691
+
692
+ // dualHostMeta: block attribute key → ACF/post meta key (from pickEditable maps)
693
+ const dualHostByBlock = {};
694
+ for (const b of blockSlugs) {
695
+ if (
696
+ b.dualHostMeta &&
697
+ typeof b.dualHostMeta === 'object' &&
698
+ Object.keys(b.dualHostMeta).length
699
+ ) {
700
+ dualHostByBlock[b.name] = b.dualHostMeta;
701
+ }
702
+ }
703
+ const dualHostJson = JSON.stringify(dualHostByBlock);
704
+
705
+ blocksRegistration = `
706
+ /**
707
+ * Register dynamic Gutenberg blocks compiled by ForgeWP.
708
+ */
709
+ function forgewp_register_dynamic_blocks(): void {
710
+ $blocks = array(${blockSlugs.map((s) => `'${s.name.replace('forgewp/', '')}'`).join(', ')});
711
+ foreach ($blocks as $block) {
712
+ register_block_type(__DIR__ . '/blocks/' . $block);
713
+ }
714
+ }
715
+ add_action('init', 'forgewp_register_dynamic_blocks');
716
+ ${categoriesHook}
717
+ /**
718
+ * Dual-host sync: when a ForgeWP block with pickEditable fields is saved in
719
+ * post content, copy attribute values into post meta (ACF keys).
720
+ *
721
+ * Baked page templates read useWpMeta / ACF — without this, editor block edits
722
+ * never reach the visitor. Attribute name (e.g. stat1Value) maps to meta key
723
+ * (e.g. trust_stat1_value) via dualHostMeta from pickEditable maps.
724
+ *
725
+ * Runs late (priority 99). Only syncs a field when the BLOCK's own attribute
726
+ * value has actually changed since the last time this hook saw it (tracked
727
+ * in a shadow map) — otherwise a block that's simply present but untouched
728
+ * would keep re-writing its stale value over an edit made directly via the
729
+ * ACF metabox in the same request. A genuine same-request conflict (both
730
+ * the block AND the ACF field edited together) still resolves to the block
731
+ * value, matching the original intent for that narrower case.
732
+ */
733
+ function forgewp_sync_dual_host_block_meta( $post_id ): void {
734
+ if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
735
+ return;
736
+ }
737
+ if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
738
+ return;
739
+ }
740
+ // REST / CLI saves may not have a capability user in every context; only
741
+ // skip when we can positively determine the user cannot edit.
742
+ if ( is_user_logged_in() && ! current_user_can( 'edit_post', $post_id ) ) {
743
+ return;
744
+ }
745
+ $map_by_block = json_decode( <<<'FORGEWP_DUAL_HOST'
746
+ ${dualHostJson}
747
+ FORGEWP_DUAL_HOST
748
+ , true );
749
+ if ( ! is_array( $map_by_block ) || empty( $map_by_block ) ) {
750
+ return;
751
+ }
752
+ $post = get_post( $post_id );
753
+ if ( ! $post || empty( $post->post_content ) ) {
754
+ return;
755
+ }
756
+ if ( ! function_exists( 'parse_blocks' ) ) {
757
+ return;
758
+ }
759
+ $blocks = parse_blocks( $post->post_content );
760
+ if ( ! is_array( $blocks ) ) {
761
+ return;
762
+ }
763
+ $write_meta = static function( $post_id, $meta_key, $val ): void {
764
+ // Prefer ACF so field formatting / reference keys stay consistent.
765
+ if ( function_exists( 'update_field' ) ) {
766
+ // update_field returns false on missing field definition; fall through.
767
+ $ok = update_field( $meta_key, $val, $post_id );
768
+ if ( $ok !== false ) {
769
+ return;
770
+ }
771
+ }
772
+ update_post_meta( $post_id, $meta_key, $val );
773
+ if ( function_exists( 'acf_get_field' ) || function_exists( 'get_field' ) ) {
774
+ update_post_meta( $post_id, '_' . $meta_key, 'field_' . $meta_key );
775
+ }
776
+ };
777
+ $shadow_key = '_forgewp_dual_host_shadow';
778
+ $shadow = get_post_meta( $post_id, $shadow_key, true );
779
+ if ( ! is_array( $shadow ) ) {
780
+ $shadow = array();
781
+ }
782
+ $shadow_changed = false;
783
+ $walk = function( $list ) use ( &$walk, $map_by_block, $post_id, $write_meta, &$shadow, &$shadow_changed ) {
784
+ foreach ( $list as $block ) {
785
+ if ( empty( $block['blockName'] ) ) {
786
+ if ( ! empty( $block['innerBlocks'] ) ) {
787
+ $walk( $block['innerBlocks'] );
788
+ }
789
+ continue;
790
+ }
791
+ $name = $block['blockName'];
792
+ if ( isset( $map_by_block[ $name ] ) && is_array( $map_by_block[ $name ] ) ) {
793
+ $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();
794
+ foreach ( $map_by_block[ $name ] as $attr_key => $meta_key ) {
795
+ if ( ! is_string( $meta_key ) || $meta_key === '' ) {
796
+ continue;
797
+ }
798
+ // Only keys present in the serialized block — unchanged
799
+ // defaults may be omitted by WP and must not wipe meta.
800
+ if ( ! array_key_exists( $attr_key, $attrs ) ) {
801
+ continue;
802
+ }
803
+ $block_val = $attrs[ $attr_key ];
804
+ $block_val_changed = ! array_key_exists( $meta_key, $shadow ) || $shadow[ $meta_key ] !== $block_val;
805
+ if ( $block_val_changed ) {
806
+ $write_meta( $post_id, $meta_key, $block_val );
807
+ $shadow[ $meta_key ] = $block_val;
808
+ $shadow_changed = true;
809
+ }
810
+ }
811
+ }
812
+ if ( ! empty( $block['innerBlocks'] ) ) {
813
+ $walk( $block['innerBlocks'] );
814
+ }
815
+ }
816
+ };
817
+ $walk( $blocks );
818
+ if ( $shadow_changed ) {
819
+ update_post_meta( $post_id, $shadow_key, $shadow );
820
+ }
821
+ }
822
+ add_action( 'save_post', 'forgewp_sync_dual_host_block_meta', 99, 1 );
823
+ // Block editor REST saves also fire save_post; these are belt-and-suspenders.
824
+ add_action( 'rest_after_insert_post', function( $post ) {
825
+ if ( $post instanceof WP_Post ) {
826
+ forgewp_sync_dual_host_block_meta( (int) $post->ID );
827
+ }
828
+ }, 20, 1 );
829
+ add_action( 'rest_after_insert_page', function( $post ) {
830
+ if ( $post instanceof WP_Post ) {
831
+ forgewp_sync_dual_host_block_meta( (int) $post->ID );
832
+ }
833
+ }, 20, 1 );
834
+
835
+ /**
836
+ * Enqueue Block Editor JavaScript to dynamically render block interfaces.
837
+ */
838
+ function forgewp_enqueue_block_editor_assets(): void {
839
+ wp_enqueue_script(
840
+ 'forgewp-editor-script',
841
+ get_template_directory_uri() . '/assets/forgewp-editor.js',
842
+ array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render', 'wp-plugins', 'wp-editor', 'wp-edit-post', 'wp-data', 'wp-core-data'),
843
+ file_exists(get_template_directory() . '/assets/forgewp-editor.js') ? filemtime(get_template_directory() . '/assets/forgewp-editor.js') : FORGEWP_THEME_VERSION,
844
+ true
845
+ );
846
+
847
+ wp_localize_script(
848
+ 'forgewp-editor-script',
849
+ 'forgeWpBlocks',
850
+ json_decode(<<<'FORGEWP_BLOCKS'
851
+ ${JSON.stringify(blockSlugs.map(({ edit: _e, render: _r, ...b }) => b))}
852
+ FORGEWP_BLOCKS
853
+ )
854
+ );
855
+
856
+ $editor_css_path = get_template_directory() . '/assets/${css}';
857
+ $editor_css = '';
858
+ if (file_exists($editor_css_path)) {
859
+ $editor_css = file_get_contents($editor_css_path);
860
+ $editor_css = preg_replace('/^@import\\s*(?:url\\([^)]+\\)|"[^"]+"|\\\'[^\\\']+\\\')\\s*;/m', '', $editor_css);
861
+ }
862
+ wp_add_inline_script(
863
+ 'forgewp-editor-script',
864
+ 'window.forgeWpEditorCss = ' . wp_json_encode($editor_css) . '; ' .
865
+ 'window.forgeWpEditorConfig = Object.assign(window.forgeWpEditorConfig || {}, ' .
866
+ wp_json_encode(array('themeUri' => get_template_directory_uri())) . ');',
867
+ 'before'
868
+ );
869
+ }
870
+ add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets');
871
+
872
+ function forgewp_enqueue_block_styles(): void {
873
+ wp_enqueue_style(
874
+ 'forgewp-editor-styles',
875
+ get_template_directory_uri() . '/assets/${css}',
876
+ array(),
877
+ FORGEWP_THEME_VERSION
878
+ );
879
+ if (is_admin()) {
880
+ wp_add_inline_style(
881
+ 'forgewp-editor-styles',
882
+ '.editor-styles-wrapper .wp-block[class*="forgewp"] { overflow: visible; min-height: unset; }'
883
+ );
884
+ }
885
+ }
886
+ add_action('enqueue_block_assets', 'forgewp_enqueue_block_styles');
887
+
888
+ function forgewp_setup_editor_styles(): void {
889
+ add_theme_support('editor-styles');
890
+ add_editor_style('assets/${css}');
891
+ }
892
+ add_action('after_setup_theme', 'forgewp_setup_editor_styles');
893
+ `;
894
+ }
895
+
896
+ let registerMenusPhp = '';
897
+ const menuLocations = Object.keys(menus).filter((k) => !k.startsWith('_'));
898
+ if (menuLocations.length > 0) {
899
+ registerMenusPhp = `
900
+ // Register custom navigation menus from sitemap config
901
+ register_nav_menus(array(
902
+ ${menuLocations.map((loc) => ` '${loc}' => __('${loc.charAt(0).toUpperCase() + loc.slice(1)} Navigation', '${config.textDomain}'),`).join('\n')}
903
+ ));`;
904
+ }
905
+
906
+ const pagesPhpArray = pagesToAutoCreate
907
+ .map((p) => {
908
+ const lines = [
909
+ ` 'title' => '${p.title.replace(/'/g, "\\'")}',`,
910
+ ` 'slug' => '${p.slug.replace(/'/g, "\\'")}',`,
911
+ ` 'template' => '${p.template.replace(/'/g, "\\'")}',`,
912
+ ];
913
+ if (p.description) {
914
+ lines.push(
915
+ ` 'description' => '${p.description.replace(/'/g, "\\'")}',`,
916
+ );
917
+ }
918
+ return ` array(\n${lines.join('\n')}\n )`;
919
+ })
920
+ .join(',\n');
921
+
922
+ function serializeMenuItemToPhp(item, indent = 16) {
923
+ const pad = ' '.repeat(indent);
924
+ const title = (item.title || '').replace(/'/g, "\\'");
925
+ const url = (item.url || '').replace(/'/g, "\\'");
926
+ const lines = [`${pad}'title' => '${title}'`, `${pad}'url' => '${url}'`];
927
+ if (item.target) {
928
+ lines.push(
929
+ `${pad}'target' => '${String(item.target).replace(/'/g, "\\'")}'`,
930
+ );
931
+ }
932
+ if (item.description) {
933
+ lines.push(
934
+ `${pad}'description' => '${String(item.description).replace(/'/g, "\\'")}'`,
935
+ );
936
+ }
937
+ if (item.attrTitle) {
938
+ lines.push(
939
+ `${pad}'attrTitle' => '${String(item.attrTitle).replace(/'/g, "\\'")}'`,
940
+ );
941
+ }
942
+ if (
943
+ item.classes &&
944
+ Array.isArray(item.classes) &&
945
+ item.classes.length > 0
946
+ ) {
947
+ const classStrs = item.classes
948
+ .map((c) => `'${String(c).replace(/'/g, "\\'")}'`)
949
+ .join(', ');
950
+ lines.push(`${pad}'classes' => array(${classStrs})`);
951
+ }
952
+ if (item.badge) {
953
+ lines.push(
954
+ `${pad}'badge' => '${String(item.badge).replace(/'/g, "\\'")}'`,
955
+ );
956
+ }
957
+ if (item.image) {
958
+ lines.push(
959
+ `${pad}'image' => '${String(item.image).replace(/'/g, "\\'")}'`,
960
+ );
961
+ }
962
+ if (item.icon) {
963
+ lines.push(`${pad}'icon' => '${String(item.icon).replace(/'/g, "\\'")}'`);
964
+ }
965
+ if (
966
+ item.children &&
967
+ Array.isArray(item.children) &&
968
+ item.children.length > 0
969
+ ) {
970
+ const childrenPhp = item.children
971
+ .map((c) => serializeMenuItemToPhp(c, indent + 4))
972
+ .join(',\n');
973
+ lines.push(`${pad}'children' => array(\n${childrenPhp}\n${pad})`);
974
+ }
975
+ return `${' '.repeat(indent - 4)}array(\n${lines.join(',\n')}\n${' '.repeat(indent - 4)})`;
976
+ }
977
+
978
+ const menuItemsPhpArray = Object.entries(menus)
979
+ .filter(([loc]) => !loc.startsWith('_'))
980
+ .map(([loc, items]) => {
981
+ const itemsPhp = (Array.isArray(items) ? items : [])
982
+ .map((item) => serializeMenuItemToPhp(item, 16))
983
+ .join(',\n');
984
+ return ` '${loc}' => array(\n${itemsPhp}\n )`;
985
+ })
986
+ .join(',\n');
987
+
988
+ const schemaDefaultsPhpLines = [];
989
+ for (const [templateSlug, schema] of Object.entries(schemas)) {
990
+ const templateName = `page-${templateSlug}.php`;
991
+ const fieldsPhpLines = [];
992
+ for (const [key, field] of Object.entries(schema)) {
993
+ if (field && typeof field.default !== 'undefined') {
994
+ let defaultValStr = '';
995
+ if (typeof field.default === 'object') {
996
+ defaultValStr = JSON.stringify(field.default);
997
+ } else {
998
+ defaultValStr = String(field.default);
999
+ }
1000
+ const escapedVal = defaultValStr
1001
+ .replace(/\\/g, '\\\\')
1002
+ .replace(/'/g, "\\'");
1003
+ fieldsPhpLines.push(` '${key}' => '${escapedVal}',`);
1004
+ }
1005
+ }
1006
+ if (fieldsPhpLines.length > 0) {
1007
+ schemaDefaultsPhpLines.push(` '${templateName}' => array(
1008
+ ${fieldsPhpLines.join('\n')}
1009
+ )`);
1010
+ }
1011
+ }
1012
+ const schemaDefaultsPhp = schemaDefaultsPhpLines.join(',\n');
1013
+
1014
+ let manifestPairs = '';
1015
+ let optionsPairs = '';
1016
+ let themeModsPairs = '';
1017
+ let page_links_php = '';
1018
+ let repeaterFieldsPhp = '';
1019
+
1020
+ if (hydrationData && hydrationData.mapping) {
1021
+ manifestPairs = Object.entries(hydrationData.mapping)
1022
+ .map(([key, val]) => {
1023
+ const cleanVal = val.replace(/^.*?[/\\]?assets[/\\]/, '');
1024
+ return ` '${key}' => 'assets/${cleanVal}'`;
1025
+ })
1026
+ .join(',\n');
1027
+
1028
+ let siteSettingsJson = {};
1029
+ const siteSettingsPath = path.join(themeRoot, 'cms', 'site-settings.json');
1030
+ if (existsSync(siteSettingsPath)) {
1031
+ try {
1032
+ siteSettingsJson = JSON.parse(readFileSync(siteSettingsPath, 'utf8'));
1033
+ } catch (e) {
1034
+ console.warn(
1035
+ 'Failed to parse site-settings.json for hydration:',
1036
+ e.message,
1037
+ );
1038
+ }
1039
+ }
1040
+
1041
+ optionsPairs = wpOptions
1042
+ .map((opt) => {
1043
+ const defaultVal = opt.defaultValue || '';
1044
+ const phpDefault = `'${defaultVal.replace(/'/g, "\\'")}'`;
1045
+ return ` '${opt.name}' => get_option('${opt.name}', ${phpDefault})`;
1046
+ })
1047
+ .join(',\n');
1048
+
1049
+ const themeModsObj = config.themeMods || siteSettingsJson.theme_mods || {};
1050
+ const themeModKeys = Object.keys(themeModsObj);
1051
+ themeModsPairs = themeModKeys
1052
+ .map((key) => {
1053
+ const defaultVal = themeModsObj[key];
1054
+ let phpDefault = 'false';
1055
+ if (typeof defaultVal === 'string') {
1056
+ phpDefault = `'${defaultVal.replace(/'/g, "\\'")}'`;
1057
+ } else if (
1058
+ typeof defaultVal === 'number' ||
1059
+ typeof defaultVal === 'boolean'
1060
+ ) {
1061
+ phpDefault = String(defaultVal);
1062
+ } else if (typeof defaultVal === 'object' && defaultVal !== null) {
1063
+ phpDefault = 'array()';
1064
+ }
1065
+ return ` '${key}' => get_theme_mod('${key}', ${phpDefault})`;
1066
+ })
1067
+ .join(',\n');
1068
+
1069
+ const pageTemplateSlugs = pagesToAutoCreate.map((p) =>
1070
+ p.template.replace(/^page-/, '').replace(/\.php$/, ''),
1071
+ );
1072
+
1073
+ for (const slug of pageTemplateSlugs) {
1074
+ const safeVar = slug.replace(/[^a-zA-Z0-9]/g, '_');
1075
+ page_links_php += ` $__fwp_route_id_${safeVar} = forgewp_resolve_route_page_id('${slug}');
1076
+ $page_links['${slug}'] = $__fwp_route_id_${safeVar} ? get_permalink($__fwp_route_id_${safeVar}) : '';\n`;
1077
+ }
1078
+
1079
+ const repeaterFields = {};
1080
+ for (const [templateSlug, schema] of Object.entries(schemas)) {
1081
+ for (const [key, field] of Object.entries(schema)) {
1082
+ if (field.type === 'repeater' && field.fields) {
1083
+ repeaterFields[key] = Object.keys(field.fields);
1084
+ }
1085
+ }
1086
+ }
1087
+ repeaterFieldsPhp = Object.entries(repeaterFields)
1088
+ .map(([metaKey, subKeys]) => {
1089
+ const subKeysStr = subKeys.map((k) => `'${k}'`).join(', ');
1090
+ return ` '${metaKey}' => array(${subKeysStr})`;
1091
+ })
1092
+ .join(',\n');
1093
+ }
1094
+
1095
+ let headlessScript = '';
1096
+ if (config.headless) {
1097
+ const headlessApiUrl = config.headless.apiUrl || '';
1098
+ const headlessJwtAuth = !!config.headless.jwtAuth;
1099
+ headlessScript = `
1100
+ wp_add_inline_script(
1101
+ '${config.textDomain}-react-runtime',
1102
+ 'window.FORGEWP_API_URL = ' . wp_json_encode('${headlessApiUrl}') . '; window.FORGEWP_JWT_AUTH = ${headlessJwtAuth ? 'true' : 'false'};',
1103
+ 'before'
1104
+ );`;
1105
+ }
1106
+
1107
+ const themeSetupPhp = buildThemeSetupPhp(
1108
+ config,
1109
+ schemas,
1110
+ registeredTaxonomies,
1111
+ postTypes,
1112
+ uniqueMetaKeys,
1113
+ metaKeyTypes,
1114
+ metaKeysToSkip,
1115
+ socialKeys,
1116
+ defaultPasswordResetEmailSubject,
1117
+ defaultPasswordResetEmailBody,
1118
+ defaultVerificationEmailSubject,
1119
+ defaultVerificationEmailBody,
1120
+ defaultLoginField,
1121
+ defaultEmailVerificationEnabled,
1122
+ defaultRegistrationEnabled,
1123
+ defaultBlockLoginUntilVerified,
1124
+ menus,
1125
+ );
1126
+
1127
+ const routingPhp = buildRoutingPhp(
1128
+ config,
1129
+ pagesPhpArray,
1130
+ schemaDefaultsPhp,
1131
+ menuItemsPhpArray,
1132
+ socialSettingsPhp,
1133
+ postTypes,
1134
+ );
1135
+
1136
+ let mainJs = '';
1137
+ if (hydrationData && hydrationData.mainJsFile) {
1138
+ mainJs = hydrationData.mainJsFile.replace(/^.*?[/\\]?assets[/\\]/, '');
1139
+ }
1140
+
1141
+ let providersPhp = '';
1142
+ const layoutProviders = themeRoot ? scanAppProviders(themeRoot) : [];
1143
+ if (layoutProviders.length > 0) {
1144
+ const pKeys = layoutProviders.map((p) => `'${p.kebab}'`).join(', ');
1145
+ providersPhp = `\n 'providers' => array(${pKeys}),`;
1146
+ }
1147
+
1148
+ const hydrationEnqueuerPhp = buildHydrationEnqueuerPhp(
1149
+ config,
1150
+ assets,
1151
+ mainJs,
1152
+ uniqueMetaKeys,
1153
+ uniqueRichTextKeys,
1154
+ repeaterFieldsPhp,
1155
+ manifestPairs,
1156
+ optionsPairs,
1157
+ themeModsPairs,
1158
+ page_links_php,
1159
+ fontsEnqueue,
1160
+ i18nKeysPhp,
1161
+ headlessScript,
1162
+ currentUserHydrationField,
1163
+ defaultLoginField,
1164
+ providersPhp,
1165
+ );
1166
+
1167
+ const restEndpointsPhp = buildRestEndpointsPhp(
1168
+ config,
1169
+ queries,
1170
+ hasAuth,
1171
+ defaultPasswordResetEmailSubject,
1172
+ defaultPasswordResetEmailBody,
1173
+ defaultVerificationEmailSubject,
1174
+ defaultVerificationEmailBody,
1175
+ defaultLoginField,
1176
+ defaultEmailVerificationEnabled,
1177
+ defaultRegistrationEnabled,
1178
+ defaultBlockLoginUntilVerified,
1179
+ defaultAutoLoginAfterSignup,
1180
+ defaultDefaultRole,
1181
+ reservedUsernamesPhp,
1182
+ );
1183
+
1184
+ const formsPhp = buildFormsPhp(config);
1185
+
1186
+ for (const diagnostic of collectCptRouteDiagnostics(config, postTypes, pagesToAutoCreate)) {
1187
+ const message = '[ForgeWP Routing' + (diagnostic.level === 'warning' ? ' Warning' : '') + '] ' + diagnostic.message;
1188
+ if (diagnostic.level === 'warning') console.warn(message);
1189
+ else console.log(message);
1190
+ }
1191
+ const cptRewriteFlushPhp = buildCptRewriteRefreshPhp(config, postTypes);
1192
+
1193
+ let _php = `<?php
1194
+ /**
1195
+ * ${config.name} — generated by ForgeWP
1196
+ *
1197
+ * @package ${config.textDomain}
1198
+ */
1199
+
1200
+ if (! defined('ABSPATH')) {
1201
+ exit;
1202
+ }
1203
+
1204
+ ${themeSetupPhp}
1205
+
1206
+ ${routingPhp}
1207
+
1208
+ ${hydrationEnqueuerPhp}
1209
+
1210
+ ${seoPluginsPhp}
1211
+
1212
+ ${preconnectFilter}
1213
+
1214
+ ${blocksRegistration}
1215
+
1216
+ ${cptRegistration}
1217
+
1218
+ ${cptRewriteFlushPhp}
1219
+
1220
+ ${restEndpointsPhp}
1221
+
1222
+ ${formsPhp}
1223
+
1224
+ /**
1225
+ * Helper to fetch any repeater field, bypassing ACF internal formatting if needed.
1226
+ */
1227
+ function forgewp_get_repeater_field($meta_key, $sub_field_keys, $post_id = null) {
1228
+ if (!$post_id) {
1229
+ $post_id = get_the_ID();
1230
+ }
1231
+ if (!$post_id) {
1232
+ return array();
1233
+ }
1234
+
1235
+ $rows = array();
1236
+
1237
+ // 1. Try get_field first
1238
+ if (function_exists('get_field')) {
1239
+ $val = get_field($meta_key, $post_id);
1240
+ if (is_array($val) && !empty($val)) {
1241
+ $rows = $val;
1242
+ }
1243
+ }
1244
+
1245
+ // 2. Direct DB query using ACF structure
1246
+ if (empty($rows)) {
1247
+ $count = get_post_meta($post_id, $meta_key, true);
1248
+ if (is_numeric($count) && intval($count) > 0) {
1249
+ $count = intval($count);
1250
+ for ($i = 0; $i < $count; $i++) {
1251
+ $row = array();
1252
+ foreach ($sub_field_keys as $sub_key) {
1253
+ $sub_val = get_post_meta($post_id, "{$meta_key}_{$i}_{$sub_key}", true);
1254
+ if (is_string($sub_val) && (strpos($sub_val, '[') === 0 || strpos($sub_val, '{') === 0)) {
1255
+ $decoded = json_decode($sub_val, true);
1256
+ if (is_array($decoded)) {
1257
+ $sub_val = $decoded;
1258
+ }
1259
+ }
1260
+ $row[$sub_key] = $sub_val;
1261
+ }
1262
+ $rows[] = $row;
1263
+ }
1264
+ }
1265
+ }
1266
+
1267
+ // 3. Fallback to json_fallback
1268
+ if (empty($rows)) {
1269
+ $fallback = get_post_meta($post_id, "{$meta_key}_json_fallback", true);
1270
+ if (is_string($fallback) && !empty($fallback)) {
1271
+ $decoded = json_decode($fallback, true);
1272
+ if (is_array($decoded)) {
1273
+ $rows = $decoded;
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ // 4. Raw JSON fallback
1279
+ if (empty($rows)) {
1280
+ $raw_meta = get_post_meta($post_id, $meta_key, true);
1281
+ if (is_string($raw_meta) && !empty($raw_meta)) {
1282
+ $decoded = json_decode($raw_meta, true);
1283
+ if (is_array($decoded)) {
1284
+ $rows = $decoded;
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // Normalize rows to resolve image arrays/IDs to URLs
1290
+ if (is_array($rows)) {
1291
+ foreach ($rows as $index => $row) {
1292
+ if (is_array($row)) {
1293
+ foreach ($row as $sub_key => $sub_val) {
1294
+ if (is_string($sub_val) && (strpos($sub_val, '[') === 0 || strpos($sub_val, '{') === 0)) {
1295
+ $decoded = json_decode($sub_val, true);
1296
+ if (is_array($decoded)) {
1297
+ $sub_val = $decoded;
1298
+ }
1299
+ }
1300
+
1301
+ if (is_array($sub_val) && isset($sub_val['url'])) {
1302
+ $sub_val = $sub_val['url'];
1303
+ } elseif (is_numeric($sub_val) && intval($sub_val) > 0 && get_post_type(intval($sub_val)) === 'attachment') {
1304
+ $url = wp_get_attachment_image_url(intval($sub_val), 'full');
1305
+ if ($url) {
1306
+ $sub_val = $url;
1307
+ }
1308
+ }
1309
+
1310
+ $rows[$index][$sub_key] = $sub_val;
1311
+ }
1312
+ }
1313
+ }
1314
+ }
1315
+
1316
+ return is_array($rows) ? $rows : array();
1317
+ }
1318
+
1319
+ /**
1320
+ * Resolves a ForgeWP route slug (e.g. "kontakt-page") to a WP post ID for the
1321
+ * current Polylang language, if any. Anchors on the "forgewp_route_id" post
1322
+ * meta set once at page-creation time (see forgewp_auto_create_pages_and_menus
1323
+ * in routing.js) rather than on the page's assigned template, because the
1324
+ * template is user-editable in wp-admin (e.g. switching a page to a generic
1325
+ * block-based template) and doing so must not break link resolution. Falls
1326
+ * back to the legacy "_wp_page_template" match for pages created before the
1327
+ * route-id marker existed. Once an anchor page is found, in any language,
1328
+ * resolves to the requested language's translation via Polylang — this means
1329
+ * only ONE language's page needs to carry the marker/template for every
1330
+ * language's link to resolve correctly.
1331
+ */
1332
+ function forgewp_resolve_route_page_id($route_slug) {
1333
+ $anchor_pages = get_pages(array(
1334
+ 'meta_key' => 'forgewp_route_id',
1335
+ 'meta_value' => $route_slug,
1336
+ 'number' => 1,
1337
+ // 'lang' => '': this lookup must search ALL languages to find the
1338
+ // anchor page, regardless of which language is currently being
1339
+ // viewed — without this, Polylang silently and implicitly restricts
1340
+ // get_pages() to the current page's language, so an anchor tagged
1341
+ // only on the German page would invisibly disappear from this query
1342
+ // while rendering an English page.
1343
+ 'lang' => '',
1344
+ ));
1345
+ $anchor_id = !empty($anchor_pages) ? $anchor_pages[0]->ID : 0;
1346
+
1347
+ if (!$anchor_id) {
1348
+ $template_pages = get_pages(array(
1349
+ 'meta_key' => '_wp_page_template',
1350
+ 'meta_value' => "page-{$route_slug}.php",
1351
+ 'number' => 1,
1352
+ 'lang' => '',
1353
+ ));
1354
+ $anchor_id = !empty($template_pages) ? $template_pages[0]->ID : 0;
1355
+ }
1356
+
1357
+ if (!$anchor_id) {
1358
+ return 0;
1359
+ }
1360
+
1361
+ $target_id = $anchor_id;
1362
+ if (function_exists('pll_get_post')) {
1363
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1364
+ if (!empty($current_lang)) {
1365
+ $translated_id = pll_get_post($anchor_id, $current_lang);
1366
+ if ($translated_id) {
1367
+ $target_id = $translated_id;
1368
+ }
1369
+ }
1370
+ }
1371
+
1372
+ return $target_id;
1373
+ }
1374
+
1375
+ /**
1376
+ * Helper to resolve a page's URL by its ForgeWP route slug. Used by Gutenberg
1377
+ * block components, which reference useWpPageLink() as plain source text and
1378
+ * can't go through the page-level token/regex substitution pipeline.
1379
+ */
1380
+ function forgewp_resolve_page_link($slug, $fallback = '') {
1381
+ $target_id = forgewp_resolve_route_page_id($slug);
1382
+ return $target_id ? get_permalink($target_id) : $fallback;
1383
+ }
1384
+
1385
+ /**
1386
+ * Resolves "the front page" for the CURRENT language — used anywhere a
1387
+ * value needs to be read from the front page's own post meta while NOT
1388
+ * necessarily viewing the front page itself (e.g. a front-page-sourced icon
1389
+ * or meta value referenced from another template). get_option('page_on_front')
1390
+ * alone is not reliable for this: it's a single, raw post ID, and whether
1391
+ * Polylang transparently translates it per-request depends on how the
1392
+ * site's per-language homepages were set up — this resolves it explicitly
1393
+ * instead of assuming, the same way forgewp_resolve_route_page_id() does
1394
+ * for named routes.
1395
+ *
1396
+ * If you're already IN a front-page request (is_front_page() is true), use
1397
+ * get_queried_object_id() instead — that's WordPress's own resolution of
1398
+ * what's actually being displayed right now, and doesn't need this at all.
1399
+ */
1400
+ function forgewp_resolve_front_page_id() {
1401
+ $anchor_id = (int) get_option('page_on_front');
1402
+ if (!$anchor_id) {
1403
+ return 0;
1404
+ }
1405
+
1406
+ $target_id = $anchor_id;
1407
+ if (function_exists('pll_get_post')) {
1408
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1409
+ if (!empty($current_lang)) {
1410
+ $translated_id = pll_get_post($anchor_id, $current_lang);
1411
+ if ($translated_id) {
1412
+ $target_id = $translated_id;
1413
+ }
1414
+ }
1415
+ }
1416
+
1417
+ return $target_id;
1418
+ }
1419
+
1420
+ /**
1421
+ * PHP counterpart of src/lib/section-padding.ts's sectionPaddingY(). render.php
1422
+ * has no JS runtime to fall back on, so cross-file dual-host layout helpers like
1423
+ * this one need a first-class PHP twin rather than being silently neutralized.
1424
+ * Keep the padding-token map in sync with SECTION_PADDING_Y in that file.
1425
+ */
1426
+ function forgewp_section_padding_y($value, $fallback = 'md') {
1427
+ $map = array(
1428
+ 'none' => '',
1429
+ 'sm' => 'py-4 sm:py-6',
1430
+ 'md' => 'py-8 sm:py-10',
1431
+ 'lg' => 'py-12 sm:py-16',
1432
+ );
1433
+ if (!empty($value) && isset($map[$value])) {
1434
+ return $map[$value];
1435
+ }
1436
+ return isset($map[$fallback]) ? $map[$fallback] : '';
1437
+ }
1438
+
1439
+ /**
1440
+ * Every ForgeWP block automatically gets paddingY/paddingX attributes and this
1441
+ * helper resolves both into Tailwind classes, applied directly to the block's
1442
+ * own top-level element by the compiler — no per-block wiring needed. Replaces
1443
+ * the old pattern of importing resolveBlockPaddingY()/sectionPaddingY() from a
1444
+ * shared lib file per block, which required translating arbitrary cross-file
1445
+ * JS helpers into PHP and was a recurring source of bugs.
1446
+ */
1447
+ function forgewp_padding_classes($attributes) {
1448
+ $py_map = array(
1449
+ 'none' => '',
1450
+ 'sm' => 'py-4 sm:py-6',
1451
+ 'md' => 'py-8 sm:py-10',
1452
+ 'lg' => 'py-12 sm:py-16',
1453
+ );
1454
+ $px_map = array(
1455
+ 'none' => '',
1456
+ 'sm' => 'px-4',
1457
+ 'md' => 'px-4 sm:px-6',
1458
+ 'lg' => 'px-4 sm:px-6 lg:px-8',
1459
+ );
1460
+ $py_value = isset($attributes['paddingY']) ? $attributes['paddingY'] : 'none';
1461
+ $px_value = isset($attributes['paddingX']) ? $attributes['paddingX'] : 'none';
1462
+ $py = isset($py_map[$py_value]) ? $py_map[$py_value] : '';
1463
+ $px = isset($px_map[$px_value]) ? $px_map[$px_value] : '';
1464
+ return trim($py . ' ' . $px);
1465
+ }
1466
+
1467
+ /**
1468
+ * Resolve ForgeWP image sources consistently for server-rendered blocks.
1469
+ */
1470
+ function forgewp_resolve_image_source($source, $size = 'full') {
1471
+ $size = is_string($size) ? sanitize_key($size) : 'full';
1472
+ if ($size === '') {
1473
+ $size = 'full';
1474
+ }
1475
+
1476
+ if (is_array($source)) {
1477
+ if (isset($source['sizes'][$size]['url'])) {
1478
+ $source = $source['sizes'][$size]['url'];
1479
+ } elseif (isset($source['url'])) {
1480
+ $source = $source['url'];
1481
+ } elseif (isset($source['src'])) {
1482
+ $source = $source['src'];
1483
+ } elseif (isset($source['id'])) {
1484
+ $source = $source['id'];
1485
+ } else {
1486
+ $source = '';
1487
+ }
1488
+ } elseif (is_object($source)) {
1489
+ if (isset($source->sizes->$size->url)) {
1490
+ $source = $source->sizes->$size->url;
1491
+ } elseif (isset($source->url)) {
1492
+ $source = $source->url;
1493
+ } elseif (isset($source->src)) {
1494
+ $source = $source->src;
1495
+ } elseif (isset($source->id)) {
1496
+ $source = $source->id;
1497
+ } else {
1498
+ $source = '';
1499
+ }
1500
+ }
1501
+
1502
+ if (is_numeric($source) && intval($source) > 0 && get_post_type(intval($source)) === 'attachment') {
1503
+ $attachment_url = wp_get_attachment_image_url(intval($source), sanitize_key($size));
1504
+ return $attachment_url ? $attachment_url : '';
1505
+ }
1506
+ if (!is_string($source)) {
1507
+ return '';
1508
+ }
1509
+
1510
+ $source = trim($source);
1511
+ if ($source === '') {
1512
+ return '';
1513
+ }
1514
+ if (preg_match('#^(?:https?:)?//#i', $source) || preg_match('#^(?:data|blob):#i', $source)) {
1515
+ return $source;
1516
+ }
1517
+
1518
+ $asset_path = preg_replace('#^(?:/|\\./|@/)+#', '', $source);
1519
+ return get_theme_file_uri($asset_path);
1520
+ }
1521
+
1522
+ /**
1523
+ * Helper to fetch and format page/post meta fields, resolving ACF formatting and attachments.
1524
+ */
1525
+ function forgewp_get_meta_value($key, $default_val = '', $is_rich_text = false, $post_id = null, $escape = true) {
1526
+ if ($post_id === null || $post_id === false || $post_id === '') {
1527
+ $post_id = get_the_ID();
1528
+ }
1529
+ if (!$post_id) {
1530
+ return $default_val;
1531
+ }
1532
+
1533
+ $val = null;
1534
+
1535
+ // 1. Try get_field first if ACF is active
1536
+ if (function_exists('get_field')) {
1537
+ $val = get_field($key, $post_id);
1538
+ }
1539
+
1540
+ // 2. Direct get_post_meta fallback
1541
+ if ($val === null || $val === false) {
1542
+ $val = get_post_meta($post_id, $key, true);
1543
+ }
1544
+
1545
+ // 3. Fallback to default if empty
1546
+ if ($val === null || $val === false || $val === '') {
1547
+ return $default_val;
1548
+ }
1549
+
1550
+ // 4. Resolve Image Arrays / Objects (ACF formats)
1551
+ if (is_array($val) && isset($val['url'])) {
1552
+ $val = $val['url'];
1553
+ }
1554
+ // 5. Resolve Attachment IDs to URLs
1555
+ elseif (is_numeric($val) && intval($val) > 0 && get_post_type(intval($val)) === 'attachment') {
1556
+ $url = wp_get_attachment_image_url(intval($val), 'full');
1557
+ if ($url) {
1558
+ $val = $url;
1559
+ }
1560
+ }
1561
+
1562
+ // 6. Format and escape
1563
+ if ($is_rich_text) {
1564
+ return wpautop($val);
1565
+ } else {
1566
+ return $escape ? esc_html($val) : $val;
1567
+ }
1568
+ }
1569
+
1570
+ /**
1571
+ * Resolves the menu ID for a location and language, using WordPress nav menu locations.
1572
+ */
1573
+ function forgewp_get_menu_id_for_lang($location, $lang = '') {
1574
+ $locations = get_nav_menu_locations();
1575
+
1576
+ if (empty($locations) || !is_array($locations)) {
1577
+ return null;
1578
+ }
1579
+
1580
+ // 1. Try to find the language-specific location key (e.g. primary___de)
1581
+ if (!empty($lang)) {
1582
+ $lang_key = $location . '___' . $lang;
1583
+ if (isset($locations[$lang_key])) {
1584
+ return $locations[$lang_key];
1585
+ }
1586
+ }
1587
+
1588
+ // 2. Try to find the base location key (e.g. primary)
1589
+ if (isset($locations[$location])) {
1590
+ return $locations[$location];
1591
+ }
1592
+
1593
+ // 3. Fallback to any matching key in the locations array
1594
+ foreach ($locations as $key => $val) {
1595
+ if ($key === $location || strpos($key, $location . '___') === 0) {
1596
+ return $val;
1597
+ }
1598
+ }
1599
+
1600
+ return null;
1601
+ }
1602
+ `;
1603
+
1604
+ // Append auto-generated Theme Options admin settings page
1605
+ const settingsPagePhp = buildSettingsPagePhp(wpOptions, config);
1606
+ if (settingsPagePhp) {
1607
+ _php += '\n\n' + settingsPagePhp;
1608
+ }
1609
+
1610
+ // Append opt-in WooCommerce Products Data Seeder
1611
+ const seedProductsPhp = buildSeedProductsPhp(config, themeRoot);
1612
+ if (seedProductsPhp) {
1613
+ _php += '\n\n' + seedProductsPhp;
1614
+ }
1615
+
1616
+ // Append opt-in Mock Content (Posts/Pages/CPTs) Data Seeder
1617
+ const seedMockDataPhp = buildSeedMockDataPhp(config, themeRoot);
1618
+ if (seedMockDataPhp) {
1619
+ _php += '\n\n' + seedMockDataPhp;
1620
+ }
1621
+
1622
+ return _php;
1623
+ }