@forgewp/compiler 0.4.2 → 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 (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -1,2044 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import path from 'node:path';
3
- import {
4
- generateAcfFieldPhp,
5
- generateDynamicAcfFieldPhp,
6
- } from './php-builders.js';
7
-
8
- function generatePhpArgs(queryObj) {
9
- const phpLines = [];
10
- phpLines.push(`$args = array(`);
11
-
12
- if (queryObj.postType && typeof queryObj.postType === 'string') {
13
- phpLines.push(` 'post_type' => '${queryObj.postType}',`);
14
- } else {
15
- phpLines.push(` 'post_type' => 'post',`);
16
- }
17
-
18
- if (queryObj.postsPerPage !== undefined) {
19
- const ppp = parseInt(queryObj.postsPerPage, 10);
20
- phpLines.push(` 'posts_per_page' => ${isNaN(ppp) ? 10 : ppp},`);
21
- } else {
22
- phpLines.push(` 'posts_per_page' => 10,`);
23
- }
24
-
25
- if (queryObj.orderby) {
26
- phpLines.push(` 'orderby' => '${queryObj.orderby}',`);
27
- }
28
- if (queryObj.order) {
29
- phpLines.push(` 'order' => '${queryObj.order}',`);
30
- }
31
-
32
- if (queryObj.categoryName) {
33
- if (String(queryObj.categoryName).startsWith('__DYNAMIC_')) {
34
- const varName = String(queryObj.categoryName).replace(/^__DYNAMIC_/, '').replace(/__$/, '');
35
- phpLines.push(` 'category_name' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
36
- } else {
37
- phpLines.push(` 'category_name' => '${queryObj.categoryName}',`);
38
- }
39
- }
40
-
41
- phpLines.push(` 'paged' => $paged,`);
42
-
43
- if (queryObj.taxQuery && Array.isArray(queryObj.taxQuery) && queryObj.taxQuery.length > 0) {
44
- phpLines.push(` 'tax_query' => array(`);
45
- for (const taxQ of queryObj.taxQuery) {
46
- phpLines.push(` array(`);
47
- phpLines.push(` 'taxonomy' => '${taxQ.taxonomy}',`);
48
- phpLines.push(` 'field' => '${taxQ.field || 'slug'}',`);
49
-
50
- const termsVal = taxQ.terms;
51
- if (typeof termsVal === 'string' && termsVal.startsWith('__DYNAMIC_')) {
52
- const varName = termsVal.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
53
- phpLines.push(` 'terms' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
54
- } else if (Array.isArray(termsVal)) {
55
- const termsPhp = termsVal.map(t => typeof t === 'string' ? `'${t}'` : t).join(', ');
56
- phpLines.push(` 'terms' => array(${termsPhp}),`);
57
- } else if (typeof termsVal === 'string') {
58
- phpLines.push(` 'terms' => '${termsVal}',`);
59
- } else {
60
- phpLines.push(` 'terms' => ${termsVal},`);
61
- }
62
- phpLines.push(` ),`);
63
- }
64
- phpLines.push(` ),`);
65
- }
66
-
67
- if (queryObj.metaQuery && Array.isArray(queryObj.metaQuery) && queryObj.metaQuery.length > 0) {
68
- phpLines.push(` 'meta_query' => array(`);
69
- if (queryObj.metaRelation) {
70
- phpLines.push(` 'relation' => '${queryObj.metaRelation}',`);
71
- }
72
- for (const metaQ of queryObj.metaQuery) {
73
- phpLines.push(` array(`);
74
- phpLines.push(` 'key' => '${metaQ.key}',`);
75
- if (metaQ.compare) {
76
- phpLines.push(` 'compare' => '${metaQ.compare}',`);
77
- }
78
- if (metaQ.value !== undefined) {
79
- const val = metaQ.value;
80
- if (typeof val === 'string' && val.startsWith('__DYNAMIC_')) {
81
- const varName = val.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
82
- phpLines.push(` 'value' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
83
- } else if (typeof val === 'string') {
84
- phpLines.push(` 'value' => '${val}',`);
85
- } else {
86
- phpLines.push(` 'value' => ${val},`);
87
- }
88
- }
89
- phpLines.push(` ),`);
90
- }
91
- phpLines.push(` ),`);
92
- }
93
-
94
- phpLines.push(` );`);
95
- return phpLines.join('\n');
96
- }
97
-
98
- /**
99
- * Generate functions.php template string
100
- *
101
- * @param {import('./types.js').ForgeWPThemeConfig} config
102
- * @param {import('./types.js').ForgeWPBuildAssets} assets
103
- */
104
- export function buildFunctionsPhp(
105
- config,
106
- assets,
107
- blockSlugs = [],
108
- themeRoot = '',
109
- pagesToAutoCreate = [],
110
- menus = {},
111
- hydrationData = null,
112
- i18nKeys = [],
113
- schemas = {},
114
- queries = [],
115
- ) {
116
- const css = assets.cssFile.replace(/^assets\//, '');
117
-
118
- let seoPluginsPhp = '';
119
- if (config.seo && config.seo.plugins) {
120
- const { yoast, rankMath } = config.seo.plugins;
121
- if (yoast) {
122
- seoPluginsPhp += `
123
- /**
124
- * Automatically integrate ForgeWP enqueued schemas with Yoast SEO Schema Graph.
125
- */
126
- add_filter('wpseo_schema_graph', function($graph) {
127
- $target = forgewp_resolve_head_target();
128
- if (file_exists($target)) {
129
- ob_start();
130
- include $target;
131
- $content = ob_get_clean();
132
- if (preg_match_all('/<script type="application\\/ld\\+json">(.*?)<\\/script>/is', $content, $matches)) {
133
- foreach ($matches[1] as $json_str) {
134
- $decoded = json_decode(trim($json_str), true);
135
- if (is_array($decoded) && is_array($graph)) {
136
- $graph[] = $decoded;
137
- }
138
- }
139
- }
140
- }
141
- return $graph;
142
- });
143
- `;
144
- }
145
- if (rankMath) {
146
- seoPluginsPhp += `
147
- /**
148
- * Automatically integrate ForgeWP enqueued schemas with RankMath JSON-LD.
149
- */
150
- add_filter('rank_math/json_ld', function($data, $jsonld) {
151
- $target = forgewp_resolve_head_target();
152
- if (file_exists($target)) {
153
- ob_start();
154
- include $target;
155
- $content = ob_get_clean();
156
- if (preg_match_all('/<script type="application\\/ld\\+json">(.*?)<\\/script>/is', $content, $matches)) {
157
- foreach ($matches[1] as $json_str) {
158
- $decoded = json_decode(trim($json_str), true);
159
- if (is_array($decoded) && is_array($data)) {
160
- $data[] = $decoded;
161
- }
162
- }
163
- }
164
- }
165
- return $data;
166
- }, 99, 2);
167
- `;
168
- }
169
- }
170
-
171
- // Built-in Favicon Support
172
- let faviconPhp = '';
173
- if (config.favicon) {
174
- const faviconPath = config.favicon.replace(/^\//, ''); // Clean leading slash
175
- faviconPhp = `
176
- /**
177
- * Enqueue Favicon dynamically in WordPress head (generated from wp.config.ts).
178
- */
179
- function forgewp_add_favicon() {
180
- $uri = get_template_directory_uri() . '/${faviconPath}';
181
- $ext = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
182
- $type = 'image/x-icon';
183
- if ($ext === 'svg') {
184
- $type = 'image/svg+xml';
185
- } elseif ($ext === 'png') {
186
- $type = 'image/png';
187
- } elseif ($ext === 'gif') {
188
- $type = 'image/gif';
189
- } elseif ($ext === 'jpg' || $ext === 'jpeg') {
190
- $type = 'image/jpeg';
191
- }
192
- echo '<link rel="icon" type="' . esc_attr($type) . '" href="' . esc_url($uri) . '">';
193
- }
194
- add_action('wp_head', 'forgewp_add_favicon');
195
- `;
196
- }
197
-
198
- // Built-in XML Segmented Sitemaps
199
- let sitemapsPhp = '';
200
- if (config.seo && config.seo.sitemaps) {
201
- const { postTypes = [], taxonomies = [] } = config.seo.sitemaps;
202
-
203
- let postTypesLines = '';
204
- for (const pt of postTypes) {
205
- postTypesLines += ` $post_types['${pt}'] = get_post_type_object('${pt}');\n`;
206
- }
207
-
208
- let taxonomiesLines = '';
209
- for (const tax of taxonomies) {
210
- taxonomiesLines += ` $taxonomies['${tax}'] = get_taxonomy('${tax}');\n`;
211
- }
212
-
213
- sitemapsPhp = `
214
- /**
215
- * Custom XML Segmented Sitemaps Configuration (generated from wp.config.ts).
216
- */
217
- function forgewp_register_segmented_xml_sitemaps() {
218
- if (!function_exists('wp_sitemaps_get_server')) {
219
- return;
220
- }
221
- if (defined('WPSEO_VERSION') || class_exists('RankMath') || class_exists('All_in_One_SEO_Pack') || defined('AIOSEO_VERSION')) {
222
- return;
223
- }
224
-
225
- add_filter('wp_sitemaps_post_types', function($post_types) {
226
- ${postTypesLines} return $post_types;
227
- });
228
-
229
- add_filter('wp_sitemaps_taxonomies', function($taxonomies) {
230
- ${taxonomiesLines} return $taxonomies;
231
- });
232
- }
233
- add_action('init', 'forgewp_register_segmented_xml_sitemaps', 99);
234
- `;
235
- }
236
- const version = config.version.replace(/'/g, "\\'");
237
- const googleFonts = config.settings?.typography?.googleFonts || [];
238
-
239
- // Load site-settings.json to discover social media options dynamically
240
- let socialKeys = ['facebook', 'instagram', 'twitter', 'youtube', 'tiktok', 'linkedin', 'pinterest']; // default fallbacks
241
- try {
242
- const siteSettingsPath = path.join(themeRoot, 'cms', 'site-settings.json');
243
- if (existsSync(siteSettingsPath)) {
244
- const siteSettings = JSON.parse(readFileSync(siteSettingsPath, 'utf8'));
245
- const optionsKeys = Object.keys(siteSettings.options || {});
246
- const discoveredSocials = optionsKeys
247
- .filter(k => k.startsWith('social_'))
248
- .map(k => k.replace(/^social_/, ''));
249
- if (discoveredSocials.length > 0) {
250
- socialKeys = Array.from(new Set([...socialKeys, ...discoveredSocials]));
251
- }
252
- }
253
- } catch (e) {
254
- // fallback to defaults if read fails
255
- }
256
-
257
- let socialSettingsPhp = '';
258
- for (const key of socialKeys) {
259
- const optionName = `social_${key}`;
260
- const capitalizedLabel = key.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
261
- socialSettingsPhp += `
262
- // \${optionName}
263
- \$wp_customize->add_setting(
264
- '${optionName}',
265
- array(
266
- 'type' => 'option',
267
- 'default' => '',
268
- 'sanitize_callback' => 'esc_url_raw',
269
- )
270
- );
271
- \$wp_customize->add_control(
272
- '${optionName}',
273
- array(
274
- 'label' => __('${capitalizedLabel} URL', '${config.textDomain}'),
275
- 'section' => 'forgewp_social_section',
276
- 'type' => 'url',
277
- )
278
- );`;
279
- }
280
-
281
- const uniqueMetaKeys = new Set();
282
- const metaKeyTypes = {};
283
- const metaKeysToSkip = new Set();
284
-
285
- for (const [templateSlug, schema] of Object.entries(schemas)) {
286
- for (const [key, field] of Object.entries(schema)) {
287
- uniqueMetaKeys.add(key);
288
- const typeMap = {
289
- text: 'string',
290
- richText: 'string',
291
- image: 'string',
292
- boolean: 'boolean',
293
- repeater: 'string',
294
- };
295
- metaKeyTypes[key] = typeMap[field.type] || 'string';
296
- if (field.skipRegisterMeta === true || field.customType === 'relationship') {
297
- metaKeysToSkip.add(key);
298
- }
299
- }
300
- }
301
-
302
- const uniqueRichTextKeys = [];
303
- for (const [templateSlug, schema] of Object.entries(schemas)) {
304
- for (const [key, field] of Object.entries(schema)) {
305
- if (field.type === 'richText' && !uniqueRichTextKeys.includes(key)) {
306
- uniqueRichTextKeys.push(key);
307
- }
308
- }
309
- }
310
-
311
- let postTypes = [];
312
- let registeredTaxonomies = [];
313
- const polylangMetaStrings = [];
314
- for (const [templateSlug, schema] of Object.entries(schemas)) {
315
- for (const [key, field] of Object.entries(schema)) {
316
- if ((field.type === 'text' || field.type === 'richText') && field.default) {
317
- polylangMetaStrings.push(field.default);
318
- }
319
- }
320
- }
321
-
322
- const uniquePolylangStrings = Array.from(new Set([
323
- ...i18nKeys,
324
- ...polylangMetaStrings
325
- ]));
326
-
327
- const i18nKeysPhp = uniquePolylangStrings
328
- .map((k) => ` '${k.replace(/'/g, "\\'")}',`)
329
- .join('\n');
330
- const wpBlockStylesLine = config.presets?.wordpressCoreStyles === false
331
- ? ''
332
- : " add_theme_support('wp-block-styles');\n";
333
-
334
- let cptRegistration = '';
335
- try {
336
- const mockDataPath = path.join(themeRoot, 'cms', 'mock-data.json');
337
- if (existsSync(mockDataPath)) {
338
- const mockData = JSON.parse(readFileSync(mockDataPath, 'utf8'));
339
- postTypes = Object.keys(mockData).filter(
340
- (k) =>
341
- k !== 'posts' &&
342
- k !== 'pages' &&
343
- k !== 'post' &&
344
- k !== 'page' &&
345
- k !== 'menus' &&
346
- k !== 'attachment' &&
347
- !k.startsWith('_'), // Underscore-prefixed keys are taxonomy definitions, not CPTs
348
- );
349
- if (postTypes.length > 0) {
350
- // Dynamic Taxonomy Scan from post _terms
351
- const taxonomiesSet = new Set();
352
- const postTypeTaxonomies = {}; // Map postType -> Set of taxonomies
353
- const postTypeNativeTaxonomies = {}; // Map postType -> Set of native taxonomies
354
-
355
- for (const pt of postTypes) {
356
- if (pt.length > 20) {
357
- throw new Error(
358
- `Custom Post Type "${pt}" inferred from mock-data.json exceeds the WordPress limit of 20 characters. Please shorten the key.`
359
- );
360
- }
361
- postTypeTaxonomies[pt] = new Set();
362
- postTypeNativeTaxonomies[pt] = new Set();
363
- const items = mockData[pt];
364
- if (Array.isArray(items)) {
365
- for (const item of items) {
366
- if (item._terms && typeof item._terms === 'object') {
367
- for (const tax of Object.keys(item._terms)) {
368
- if (tax !== 'category' && tax !== 'post_tag') {
369
- taxonomiesSet.add(tax);
370
- postTypeTaxonomies[pt].add(tax);
371
- } else {
372
- postTypeNativeTaxonomies[pt].add(tax);
373
- }
374
- }
375
- }
376
- }
377
- }
378
- }
379
-
380
- registeredTaxonomies = Array.from(taxonomiesSet);
381
-
382
- cptRegistration = `
383
- /**
384
- * Register dynamic Custom Post Types inferred from local mock data.
385
- */
386
- function forgewp_register_custom_post_types() {
387
- ${postTypes
388
- .map(
389
- (pt) => {
390
- let singular = pt.split(/[_-]/).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
391
- let plural = singular + 's';
392
- const ptConfig = config.postTypes?.[pt];
393
- if (ptConfig?.labels?.singular) {
394
- singular = ptConfig.labels.singular;
395
- }
396
- if (ptConfig?.labels?.plural) {
397
- plural = ptConfig.labels.plural;
398
- }
399
- const nativeTaxes = Array.from(postTypeNativeTaxonomies[pt] || []);
400
- const taxonomiesLine = nativeTaxes.length > 0
401
- ? `\n 'taxonomies' => array('${nativeTaxes.join("', '")}'),`
402
- : '';
403
- const nativeTaxesCalls = nativeTaxes.map(tax => `\n register_taxonomy_for_object_type('${tax}', '${pt}');`).join('');
404
- return ` register_post_type('${pt}', array(
405
- 'labels' => array(
406
- 'name' => __('${plural}', '${config.textDomain}'),
407
- 'singular_name' => __('${singular}', '${config.textDomain}'),
408
- 'menu_name' => __('${plural}', '${config.textDomain}'),
409
- 'name_admin_bar' => __('${singular}', '${config.textDomain}'),
410
- 'add_new' => __('Add New', '${config.textDomain}'),
411
- 'add_new_item' => __('Add New ${singular}', '${config.textDomain}'),
412
- 'new_item' => __('New ${singular}', '${config.textDomain}'),
413
- 'edit_item' => __('Edit ${singular}', '${config.textDomain}'),
414
- 'view_item' => __('View ${singular}', '${config.textDomain}'),
415
- 'all_items' => __('All ${plural}', '${config.textDomain}'),
416
- 'search_items' => __('Search ${plural}', '${config.textDomain}'),
417
- 'not_found' => __('No ${plural} found.', '${config.textDomain}'),
418
- ),
419
- 'public' => true,
420
- 'has_archive' => true,
421
- 'show_in_rest'=> true,${taxonomiesLine}
422
- 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'excerpt'),
423
- 'menu_icon' => 'dashicons-admin-post',
424
- ));${nativeTaxesCalls}`;
425
- }
426
- )
427
- .join('\n')}
428
-
429
- ${registeredTaxonomies
430
- .map((tax) => {
431
- const associatedPostTypes = postTypes.filter((pt) => postTypeTaxonomies[pt].has(tax));
432
- const taxLabel = tax.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
433
- return ` register_taxonomy('${tax}', array('${associatedPostTypes.join("', '")}'), array(
434
- 'labels' => array(
435
- 'name' => '${taxLabel}s',
436
- 'singular_name' => '${taxLabel}',
437
- 'search_items' => 'Search ${taxLabel}s',
438
- 'all_items' => 'All ${taxLabel}s',
439
- 'parent_item' => 'Parent ${taxLabel}',
440
- 'parent_item_colon' => 'Parent ${taxLabel}:',
441
- 'edit_item' => 'Edit ${taxLabel}',
442
- 'update_item' => 'Update ${taxLabel}',
443
- 'add_new_item' => 'Add New ${taxLabel}',
444
- 'new_item_name' => 'New ${taxLabel} Name',
445
- 'menu_name' => '${taxLabel}s',
446
- ),
447
- 'hierarchical' => true,
448
- 'public' => true,
449
- 'show_ui' => true,
450
- 'show_admin_column' => true,
451
- 'query_var' => true,
452
- 'show_in_rest' => true,
453
- ));`;
454
- })
455
- .join('\n\n')}
456
- }
457
- add_action('init', 'forgewp_register_custom_post_types');
458
- ${(() => {
459
- const translatablePtKeys = Object.entries(config.postTypes || {})
460
- .filter(([_, ptc]) => ptc.translatable)
461
- .map(([key]) => key);
462
- let php = translatablePtKeys.length > 0
463
- ? `\n// Automatically register custom post types for Polylang translation support
464
- add_filter('pll_get_post_types', function($post_types, $is_settings) {
465
- ${translatablePtKeys.map((pt) => ` $post_types['${pt}'] = '${pt}';`).join('\n')}
466
- return $post_types;
467
- }, 10, 2);`
468
- : '';
469
-
470
- if (translatablePtKeys.length > 0) {
471
- php += `\n\n// Add REST API language filtering support for custom post types under Polylang
472
- function forgewp_rest_query_language_filter($args, $request) {
473
- $lang = $request->get_param('lang');
474
- if (!empty($lang)) {
475
- $args['lang'] = sanitize_text_field($lang);
476
- } elseif (function_exists('pll_current_language')) {
477
- $args['lang'] = pll_current_language();
478
- }
479
- return $args;
480
- }
481
- `;
482
- translatablePtKeys.forEach((pt) => {
483
- php += `add_filter('rest_${pt}_query', 'forgewp_rest_query_language_filter', 10, 2);\n`;
484
- });
485
- }
486
-
487
- if (registeredTaxonomies.length > 0) {
488
- php += `\n\n// Automatically register custom taxonomies for Polylang translation support
489
- add_filter('pll_get_taxonomies', function($taxonomies, $is_settings) {
490
- ${registeredTaxonomies.map((tax) => ` $taxonomies['${tax}'] = '${tax}';`).join('\n')}
491
- return $taxonomies;
492
- }, 10, 2);`;
493
-
494
- const taxArrayStr = registeredTaxonomies.map(tax => `'${tax}'`).join(', ');
495
- php += `\n\n// Automatically expose custom taxonomy metadata in WordPress REST API
496
- add_action('rest_api_init', function() {
497
- $taxonomies = array(${taxArrayStr});
498
- foreach ($taxonomies as $tax) {
499
- register_rest_field($tax, 'meta', array(
500
- 'get_callback' => function($term) use ($tax) {
501
- $term_id = $term['id'];
502
-
503
- // Retrieve values using ACF if available, or direct term meta as fallback
504
- $featured_image = function_exists('get_field') ? get_field('featured_image', 'term_' . $term_id) : null;
505
- $flag = function_exists('get_field') ? get_field('flag', 'term_' . $term_id) : null;
506
-
507
- if (empty($featured_image)) {
508
- $featured_image = get_term_meta($term_id, 'featured_image', true);
509
- }
510
- if (empty($flag)) {
511
- $flag = get_term_meta($term_id, 'flag', true);
512
- }
513
-
514
- return array(
515
- 'featured_image' => !empty($featured_image) ? $featured_image : '',
516
- 'flag' => !empty($flag) ? $flag : ''
517
- );
518
- },
519
- 'update_callback' => null,
520
- 'schema' => null,
521
- ));
522
- }
523
- });`;
524
- }
525
-
526
- if (translatablePtKeys.length > 0 || registeredTaxonomies.length > 0) {
527
- const ptArrayStr = translatablePtKeys.map(pt => `'${pt}'`).join(', ');
528
- const taxArrayStr = registeredTaxonomies.map(tax => `'${tax}'`).join(', ');
529
- php += `\n\n// Automatically enable Polylang translation support for custom post types and taxonomies in WP Admin settings
530
- add_action('admin_init', function() {
531
- $options = get_option('polylang');
532
- if (is_array($options)) {
533
- $modified = false;
534
-
535
- $cpts_to_enable = array(${ptArrayStr});
536
- if (!isset($options['post_types'])) {
537
- $options['post_types'] = array();
538
- }
539
- foreach ($cpts_to_enable as $cpt) {
540
- if (!in_array($cpt, $options['post_types'])) {
541
- $options['post_types'][] = $cpt;
542
- $modified = true;
543
- }
544
- }
545
-
546
- $taxonomies_to_enable = array(${taxArrayStr});
547
- if (!isset($options['taxonomies'])) {
548
- $options['taxonomies'] = array();
549
- }
550
- foreach ($taxonomies_to_enable as $tax) {
551
- if (!in_array($tax, $options['taxonomies'])) {
552
- $options['taxonomies'][] = $tax;
553
- $modified = true;
554
- }
555
- }
556
-
557
- if ($modified) {
558
- update_option('polylang', $options);
559
- flush_rewrite_rules();
560
- }
561
- }
562
- });
563
-
564
- // Automatically filter out Polylang internal hidden taxonomies from relationship fields to prevent empty selections and '0' labels
565
- add_filter('get_object_taxonomies', function($taxonomies, $object, $output) {
566
- if (is_admin() && is_array($taxonomies)) {
567
- foreach ($taxonomies as $key => $tax) {
568
- $tax_name = is_object($tax) ? $tax->name : $tax;
569
- if ($tax_name === 'post_translations' || $tax_name === 'term_translations' || strpos($tax_name, 'pll_') === 0) {
570
- unset($taxonomies[$key]);
571
- }
572
- }
573
- if ($output !== 'objects') {
574
- $taxonomies = array_values($taxonomies);
575
- }
576
- }
577
- return $taxonomies;
578
- }, 99, 3);`;
579
- }
580
- return php;
581
- })()}
582
- `;
583
- }
584
- }
585
- } catch (e) {}
586
-
587
- let fontsEnqueue = '';
588
- let preconnectFilter = '';
589
-
590
- if (googleFonts.length > 0) {
591
- const fontsParam = googleFonts
592
- .map((f) => encodeURIComponent(f))
593
- .join('&family=');
594
- fontsEnqueue = `
595
- // Enqueue Google Fonts (dynamic preset via wp.config.ts)
596
- wp_enqueue_style(
597
- '${config.textDomain}-google-fonts',
598
- 'https://fonts.googleapis.com/css2?family=${fontsParam}&display=swap',
599
- array(),
600
- null
601
- );`;
602
-
603
- preconnectFilter = `
604
- /**
605
- * Add preconnect resource hints for Google Fonts performance.
606
- */
607
- function forgewp_google_fonts_resource_hints(array $urls, string $relation_type): array {
608
- if (wp_style_is('${config.textDomain}-google-fonts', 'queue') && 'preconnect' === $relation_type) {
609
- $urls[] = array(
610
- 'href' => 'https://fonts.googleapis.com',
611
- 'crossorigin' => 'anonymous',
612
- );
613
- $urls[] = array(
614
- 'href' => 'https://fonts.gstatic.com',
615
- 'crossorigin' => 'anonymous',
616
- );
617
- }
618
- return $urls;
619
- }
620
- add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
621
- `;
622
- }
623
-
624
- let blocksRegistration = '';
625
- if (blockSlugs.length > 0) {
626
- blocksRegistration = `
627
- /**
628
- * Register dynamic Gutenberg blocks compiled by ForgeWP.
629
- */
630
- function forgewp_register_dynamic_blocks(): void {
631
- $blocks = array(${blockSlugs.map((s) => `'${s.name.replace('forgewp/', '')}'`).join(', ')});
632
- foreach ($blocks as $block) {
633
- register_block_type(__DIR__ . '/blocks/' . $block);
634
- }
635
- }
636
- add_action('init', 'forgewp_register_dynamic_blocks');
637
-
638
- /**
639
- * Enqueue Block Editor JavaScript to dynamically render block interfaces.
640
- */
641
- function forgewp_enqueue_block_editor_assets(): void {
642
- wp_enqueue_script(
643
- 'forgewp-editor-script',
644
- get_template_directory_uri() . '/assets/forgewp-editor.js',
645
- array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'),
646
- FORGEWP_THEME_VERSION,
647
- true
648
- );
649
-
650
- wp_localize_script(
651
- 'forgewp-editor-script',
652
- 'forgeWpBlocks',
653
- json_decode('${JSON.stringify(blockSlugs).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}')
654
- );
655
- }
656
- add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets');
657
- `;
658
- }
659
-
660
- let registerMenusPhp = '';
661
- const menuLocations = Object.keys(menus).filter((k) => !k.startsWith('_'));
662
- if (menuLocations.length > 0) {
663
- registerMenusPhp = `
664
- // Register custom navigation menus from sitemap config
665
- register_nav_menus(array(
666
- ${menuLocations.map((loc) => ` '${loc}' => __('${loc.charAt(0).toUpperCase() + loc.slice(1)} Navigation', '${config.textDomain}'),`).join('\n')}
667
- ));`;
668
- }
669
-
670
- const pagesPhpArray = pagesToAutoCreate
671
- .map((p) => {
672
- return ` array(
673
- 'title' => '${p.title.replace(/'/g, "\\'")}',
674
- 'slug' => '${p.slug.replace(/'/g, "\\'")}',
675
- 'template' => '${p.template.replace(/'/g, "\\'")}',
676
- )`;
677
- })
678
- .join(',\n');
679
-
680
- const menuItemsPhpArray = Object.entries(menus)
681
- .filter(([loc]) => !loc.startsWith('_'))
682
- .map(([loc, items]) => {
683
- const itemsPhp = items
684
- .map((item) => {
685
- return ` array(
686
- 'title' => '${item.title.replace(/'/g, "\\'")}',
687
- 'url' => '${item.url.replace(/'/g, "\\'")}',
688
- )`;
689
- })
690
- .join(',\n');
691
- return ` '${loc}' => array(
692
- ${itemsPhp}
693
- )`;
694
- })
695
- .join(',\n');
696
-
697
- const schemaDefaultsPhpLines = [];
698
- for (const [templateSlug, schema] of Object.entries(schemas)) {
699
- const templateName = `page-${templateSlug}.php`;
700
- const fieldsPhpLines = [];
701
- for (const [key, field] of Object.entries(schema)) {
702
- if (field && typeof field.default !== 'undefined') {
703
- let defaultValStr = '';
704
- if (typeof field.default === 'object') {
705
- defaultValStr = JSON.stringify(field.default);
706
- } else {
707
- defaultValStr = String(field.default);
708
- }
709
- const escapedVal = defaultValStr.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
710
- fieldsPhpLines.push(` '${key}' => '${escapedVal}',`);
711
- }
712
- }
713
- if (fieldsPhpLines.length > 0) {
714
- schemaDefaultsPhpLines.push(` '${templateName}' => array(
715
- ${fieldsPhpLines.join('\n')}
716
- )`);
717
- }
718
- }
719
- const schemaDefaultsPhp = schemaDefaultsPhpLines.join(',\n');
720
-
721
- const autoCreationPhp = `
722
- /**
723
- * Automatically create routes defined in menus.json and assign custom page templates upon theme activation.
724
- */
725
- function forgewp_auto_create_pages_and_menus(): void {
726
- $activated_option = '${config.textDomain}_activated_' . str_replace('.', '_', FORGEWP_THEME_VERSION);
727
- $has_run = get_option($activated_option) === 'yes';
728
-
729
- $schema_defaults = array(
730
- ${schemaDefaultsPhp}
731
- );
732
-
733
- $pages = array(
734
- ${pagesPhpArray}
735
- );
736
-
737
- foreach ($pages as $p) {
738
- $existing_page = get_page_by_path($p['slug']);
739
- $page_id = 0;
740
- if (!$existing_page) {
741
- if (!$has_run) {
742
- $page_id = wp_insert_post(array(
743
- 'post_title' => $p['title'],
744
- 'post_name' => $p['slug'],
745
- 'post_status' => 'publish',
746
- 'post_type' => 'page',
747
- ));
748
- if (!is_wp_error($page_id) && $page_id > 0) {
749
- update_post_meta($page_id, '_wp_page_template', $p['template']);
750
- }
751
- }
752
- } else {
753
- $page_id = $existing_page->ID;
754
- update_post_meta($page_id, '_wp_page_template', $p['template']);
755
- }
756
-
757
- // Phase 3: Automatically seed default post meta fields if not already populated for ALL pages using this template
758
- if (isset($schema_defaults[$p['template']])) {
759
- $matching_pages = get_posts(array(
760
- 'post_type' => 'page',
761
- 'post_status'=> 'any',
762
- 'lang' => '',
763
- 'meta_query' => array(
764
- array(
765
- 'key' => '_wp_page_template',
766
- 'value' => $p['template'],
767
- 'compare' => '='
768
- )
769
- ),
770
- 'posts_per_page' => -1
771
- ));
772
-
773
- $pages_to_seed = array();
774
- if ($page_id > 0) {
775
- $pages_to_seed[] = $page_id;
776
- }
777
- if (is_array($matching_pages)) {
778
- foreach ($matching_pages as $mp) {
779
- if (!in_array($mp->ID, $pages_to_seed)) {
780
- $pages_to_seed[] = $mp->ID;
781
- }
782
- }
783
- }
784
-
785
- foreach ($pages_to_seed as $pid) {
786
- foreach ($schema_defaults[$p['template']] as $meta_key => $default_val) {
787
- // If it is a JSON repeater, decode and seed individual ACF sub-fields
788
- if (is_string($default_val) && (strpos($default_val, '[') === 0 || strpos($default_val, '{') === 0)) {
789
- $decoded = json_decode($default_val, true);
790
- if (is_array($decoded)) {
791
- // Check if the repeater is already populated by checking its count meta
792
- $current_count = get_post_meta($pid, $meta_key, true);
793
- if (empty($current_count) || !is_numeric($current_count) || intval($current_count) === 0) {
794
- // Seed the repeater count and values
795
- update_post_meta($pid, $meta_key, count($decoded));
796
- foreach ($decoded as $index => $row) {
797
- if (is_array($row)) {
798
- foreach ($row as $sub_key => $sub_val) {
799
- update_post_meta($pid, "{$meta_key}_{$index}_{$sub_key}", $sub_val);
800
- }
801
- }
802
- }
803
-
804
- // Also store the raw JSON string as fallback for React direct hooks
805
- update_post_meta($pid, "{$meta_key}_json_fallback", $default_val);
806
- }
807
-
808
- // ALWAYS enforce ACF key reference mappings for fields to display in WP Admin
809
- update_post_meta($pid, "_{$meta_key}", "field_{$meta_key}");
810
- $count_to_map = get_post_meta($pid, $meta_key, true);
811
- if (is_numeric($count_to_map)) {
812
- for ($index = 0; $index < intval($count_to_map); $index++) {
813
- foreach (array_keys($decoded[0] ?? array()) as $sub_key) {
814
- update_post_meta($pid, "_{$meta_key}_{$index}_{$sub_key}", "field_{$meta_key}_{$sub_key}");
815
- }
816
- }
817
- }
818
- continue;
819
- }
820
- }
821
-
822
- $current_val = get_post_meta($pid, $meta_key, true);
823
- if (empty($current_val)) {
824
- update_post_meta($pid, $meta_key, $default_val);
825
- }
826
- }
827
- }
828
- }
829
- }
830
-
831
- if (!$has_run) {
832
- $menu_structure = array(
833
- ${menuItemsPhpArray}
834
- );
835
-
836
- foreach ($menu_structure as $location => $items) {
837
- $menu_name = ucfirst($location) . ' Navigation';
838
- $menu_exists = wp_get_nav_menu_object($menu_name);
839
-
840
- if (!$menu_exists) {
841
- $menu_id = wp_create_nav_menu($menu_name);
842
- if (!is_wp_error($menu_id)) {
843
- $locations = get_theme_mod('nav_menu_locations');
844
- if (!is_array($locations)) {
845
- $locations = array();
846
- }
847
- $locations[$location] = $menu_id;
848
- set_theme_mod('nav_menu_locations', $locations);
849
-
850
- foreach ($items as $item) {
851
- $item_title = $item['title'];
852
- $item_url = $item['url'];
853
-
854
- $object_id = 0;
855
- $object_type = 'custom';
856
- $target_url = $item_url;
857
-
858
- if (strpos($item_url, '/') === 0) {
859
- $slug = trim($item_url, '/');
860
- if ($slug === '') {
861
- $target_url = home_url('/');
862
- } else {
863
- $page = get_page_by_path($slug);
864
- if ($page) {
865
- $object_id = $page->ID;
866
- $object_type = 'page';
867
- $target_url = get_permalink($page->ID);
868
- } else {
869
- $target_url = home_url($item_url);
870
- }
871
- }
872
- }
873
-
874
- wp_update_nav_menu_item($menu_id, 0, array(
875
- 'menu-item-title' => $item_title,
876
- 'menu-item-url' => $target_url,
877
- 'menu-item-object-id' => $object_id,
878
- 'menu-item-object' => $object_type === 'page' ? 'page' : '',
879
- 'menu-item-type' => $object_type === 'page' ? 'post_type' : 'custom',
880
- 'menu-item-status' => 'publish',
881
- ));
882
- }
883
- }
884
- }
885
- }
886
- update_option($activated_option, 'yes');
887
- }
888
- }
889
- add_action('after_switch_theme', 'forgewp_auto_create_pages_and_menus');
890
- add_action('init', 'forgewp_auto_create_pages_and_menus', 99);
891
-
892
- /**
893
- * Register customizer settings for theme modifications (e.g., footer_text).
894
- * This allows theme mods to be managed via WordPress Customizer and WP Admin.
895
- */
896
- function forgewp_register_theme_customizer_settings($wp_customize): void {
897
- // Register footer_text theme modification
898
- $wp_customize->add_setting(
899
- 'footer_text',
900
- array(
901
- 'default' => '',
902
- 'sanitize_callback' => 'sanitize_text_field',
903
- )
904
- );
905
-
906
- $wp_customize->add_control(
907
- 'footer_text',
908
- array(
909
- 'label' => __('Footer Text', '${config.textDomain}'),
910
- 'section' => 'title_tagline',
911
- 'type' => 'textarea',
912
- 'description' => __('Custom text displayed in the theme footer.', '${config.textDomain}'),
913
- )
914
- );
915
-
916
- // ── Social Media Section ──
917
- $wp_customize->add_section(
918
- 'forgewp_social_section',
919
- array(
920
- 'title' => __('Social Media Accounts', '${config.textDomain}'),
921
- 'priority' => 35,
922
- 'description' => __('Manage your social media profile URLs.', '${config.textDomain}'),
923
- )
924
- );
925
-
926
- ${socialSettingsPhp}
927
-
928
-
929
- // ── Contact Information Section ──
930
- $wp_customize->add_section(
931
- 'forgewp_contact_section',
932
- array(
933
- 'title' => __('Contact Information', '${config.textDomain}'),
934
- 'priority' => 36,
935
- 'description' => __('Manage contact details used throughout the site.', '${config.textDomain}'),
936
- )
937
- );
938
-
939
- // contact_phone
940
- $wp_customize->add_setting(
941
- 'contact_phone',
942
- array(
943
- 'type' => 'option',
944
- 'default' => '',
945
- 'sanitize_callback' => 'sanitize_text_field',
946
- )
947
- );
948
- $wp_customize->add_control(
949
- 'contact_phone',
950
- array(
951
- 'label' => __('Phone Number', '${config.textDomain}'),
952
- 'section' => 'forgewp_contact_section',
953
- 'type' => 'text',
954
- )
955
- );
956
-
957
- // contact_email
958
- $wp_customize->add_setting(
959
- 'contact_email',
960
- array(
961
- 'type' => 'option',
962
- 'default' => '',
963
- 'sanitize_callback' => 'sanitize_email',
964
- )
965
- );
966
- $wp_customize->add_control(
967
- 'contact_email',
968
- array(
969
- 'label' => __('Email Address', '${config.textDomain}'),
970
- 'section' => 'forgewp_contact_section',
971
- 'type' => 'email',
972
- )
973
- );
974
-
975
- // contact_address
976
- $wp_customize->add_setting(
977
- 'contact_address',
978
- array(
979
- 'type' => 'option',
980
- 'default' => '',
981
- 'sanitize_callback' => 'sanitize_textarea_field',
982
- )
983
- );
984
- $wp_customize->add_control(
985
- 'contact_address',
986
- array(
987
- 'label' => __('Address', '${config.textDomain}'),
988
- 'section' => 'forgewp_contact_section',
989
- 'type' => 'textarea',
990
- )
991
- );
992
-
993
- // business_hours
994
- $wp_customize->add_setting(
995
- 'business_hours',
996
- array(
997
- 'type' => 'option',
998
- 'default' => '',
999
- 'sanitize_callback' => 'sanitize_text_field',
1000
- )
1001
- );
1002
- $wp_customize->add_control(
1003
- 'business_hours',
1004
- array(
1005
- 'label' => __('Business Hours', '${config.textDomain}'),
1006
- 'section' => 'forgewp_contact_section',
1007
- 'type' => 'text',
1008
- )
1009
- );
1010
- }
1011
- add_action('customize_register', 'forgewp_register_theme_customizer_settings');
1012
-
1013
- /**
1014
- * Set default footer_text on theme activation if not already set.
1015
- */
1016
- function forgewp_set_default_footer_text(): void {
1017
- if (!get_theme_mod('footer_text')) {
1018
- set_theme_mod('footer_text', '© ' . date('Y') . ' ' . get_bloginfo('name') . '. ' . __('All rights reserved.', '${config.textDomain}'));
1019
- }
1020
- }
1021
- add_action('after_switch_theme', 'forgewp_set_default_footer_text');
1022
- `;
1023
-
1024
- let hydrationEnqueue = '';
1025
- if (hydrationData && hydrationData.mapping) {
1026
- const mainJs = hydrationData.mainJsFile.replace(/^.*?[/\\]?assets[/\\]/, '');
1027
- const manifestPairs = Object.entries(hydrationData.mapping)
1028
- .map(([key, val]) => {
1029
- const cleanVal = val.replace(/^.*?[/\\]?assets[/\\]/, '');
1030
- return ` '${key}' => 'assets/${cleanVal}'`;
1031
- })
1032
- .join(',\n');
1033
-
1034
- // Load mock site settings for hydration payloads
1035
- let siteSettingsJson = {};
1036
- const siteSettingsPath = path.join(themeRoot, 'cms', 'site-settings.json');
1037
- if (existsSync(siteSettingsPath)) {
1038
- try {
1039
- siteSettingsJson = JSON.parse(readFileSync(siteSettingsPath, 'utf8'));
1040
- } catch (e) {
1041
- console.warn(
1042
- 'Failed to parse site-settings.json for hydration:',
1043
- e.message,
1044
- );
1045
- }
1046
- }
1047
-
1048
- // Generate dynamic PHP for options collection
1049
- const optionKeys = Object.keys(siteSettingsJson.options || {});
1050
- const optionsPairs = optionKeys
1051
- .map((key) => {
1052
- const defaultVal = siteSettingsJson.options[key];
1053
- let phpDefault = 'false';
1054
- if (typeof defaultVal === 'string') {
1055
- phpDefault = `'${defaultVal.replace(/'/g, "\\'")}'`;
1056
- } else if (typeof defaultVal === 'number' || typeof defaultVal === 'boolean') {
1057
- phpDefault = String(defaultVal);
1058
- }
1059
- return ` '${key}' => get_option('${key}', ${phpDefault})`;
1060
- })
1061
- .join(',\n');
1062
-
1063
- // Generate dynamic PHP for theme_mods collection
1064
- const themeModKeys = Object.keys(siteSettingsJson.theme_mods || {});
1065
- const themeModsPairs = themeModKeys
1066
- .map((key) => {
1067
- const defaultVal = siteSettingsJson.theme_mods[key];
1068
- let phpDefault = 'false';
1069
- if (typeof defaultVal === 'string') {
1070
- phpDefault = `'${defaultVal.replace(/'/g, "\\'")}'`;
1071
- } else if (typeof defaultVal === 'number' || typeof defaultVal === 'boolean') {
1072
- phpDefault = String(defaultVal);
1073
- } else if (typeof defaultVal === 'object' && defaultVal !== null) {
1074
- phpDefault = 'array()';
1075
- }
1076
- return ` '${key}' => get_theme_mod('${key}', ${phpDefault})`;
1077
- })
1078
- .join(',\n');
1079
-
1080
- const pageTemplateSlugs = pagesToAutoCreate.map((p) =>
1081
- p.template.replace(/^page-/, '').replace(/\.php$/, ''),
1082
- );
1083
-
1084
- let page_links_php = '';
1085
- for (const slug of pageTemplateSlugs) {
1086
- const safeVar = slug.replace(/[^a-zA-Z0-9]/g, '_');
1087
- page_links_php += ` $get_pages_args_${safeVar} = array(
1088
- 'meta_key' => '_wp_page_template',
1089
- 'meta_value' => 'page-${slug}.php',
1090
- 'number' => 1
1091
- );
1092
- if (!empty($current_lang)) {
1093
- $get_pages_args_${safeVar}['lang'] = $current_lang;
1094
- }
1095
- $matched_pages_${safeVar} = get_pages($get_pages_args_${safeVar});
1096
- $page_links['${slug}'] = !empty($matched_pages_${safeVar}) ? get_permalink($matched_pages_${safeVar}[0]->ID) : '';\n`;
1097
- }
1098
-
1099
- const repeaterFields = {};
1100
- for (const [templateSlug, schema] of Object.entries(schemas)) {
1101
- for (const [key, field] of Object.entries(schema)) {
1102
- if (field.type === 'repeater' && field.fields) {
1103
- repeaterFields[key] = Object.keys(field.fields);
1104
- }
1105
- }
1106
- }
1107
- const repeaterFieldsPhp = Object.entries(repeaterFields)
1108
- .map(([metaKey, subKeys]) => {
1109
- const subKeysStr = subKeys.map((k) => `'${k}'`).join(', ');
1110
- return ` '${metaKey}' => array(${subKeysStr})`;
1111
- })
1112
- .join(',\n');
1113
-
1114
- hydrationEnqueue = `
1115
- // Enqueue React runtime entrypoint and dynamic Selective Hydration assets
1116
- $js_path = get_template_directory() . '/assets/${mainJs}';
1117
- if (file_exists($js_path)) {
1118
- wp_enqueue_script(
1119
- '${config.textDomain}-react-runtime',
1120
- $theme_uri . '/assets/${mainJs}',
1121
- array(),
1122
- FORGEWP_THEME_VERSION,
1123
- true
1124
- );
1125
-
1126
- $menu_locations = get_nav_menu_locations();
1127
- $hydrated_menus = array();
1128
- $registered_nav_menus = get_registered_nav_menus();
1129
- $registered_locations = is_array($registered_nav_menus) ? array_keys($registered_nav_menus) : array();
1130
- $current_lang = '';
1131
- if (function_exists('pll_current_language')) {
1132
- $current_lang = pll_current_language();
1133
- } elseif (defined('ICL_LANGUAGE_CODE')) {
1134
- $current_lang = ICL_LANGUAGE_CODE;
1135
- }
1136
- if (empty($current_lang)) {
1137
- if (function_exists('pll_default_language')) {
1138
- $current_lang = pll_default_language();
1139
- } else {
1140
- $current_lang = get_locale();
1141
- if (strpos($current_lang, '_') !== false) {
1142
- $parts = explode('_', $current_lang);
1143
- $current_lang = $parts[0];
1144
- }
1145
- }
1146
- }
1147
- foreach ($registered_locations as $loc) {
1148
- $base_loc = $loc;
1149
- if (strpos($loc, '___') !== false) {
1150
- $parts = explode('___', $loc);
1151
- $base_loc = $parts[0];
1152
- }
1153
-
1154
- $menu_id = forgewp_get_menu_id_for_lang($base_loc, $current_lang);
1155
- $raw_items = $menu_id ? wp_get_nav_menu_items($menu_id) : array();
1156
- $menu_items = is_array($raw_items) ? $raw_items : array();
1157
- $items_list = array();
1158
- foreach ($menu_items as $item) {
1159
- $items_list[] = array(
1160
- 'title' => $item->title,
1161
- 'url' => $item->url
1162
- );
1163
- }
1164
- $hydrated_menus[$base_loc] = $items_list;
1165
- if (!empty($current_lang)) {
1166
- $hydrated_menus[$base_loc . '___' . $current_lang] = $items_list;
1167
- }
1168
- }
1169
-
1170
- $page_links = array();
1171
- ${page_links_php}
1172
-
1173
- // Inject hydration manifest mappings dynamically
1174
- wp_add_inline_script(
1175
- '${config.textDomain}-react-runtime',
1176
- 'window.forgeWpHydration = ' . wp_json_encode(array(
1177
- 'themeUri' => $theme_uri,
1178
- 'menus' => $hydrated_menus,
1179
- 'pageLinks' => $page_links,
1180
- 'manifest' => array(
1181
- ${manifestPairs}
1182
- ),
1183
- 'siteSettings' => array(
1184
- 'options' => array(
1185
- ${optionsPairs}
1186
- ),
1187
- 'theme_mods' => array(
1188
- ${themeModsPairs}
1189
- ),
1190
- ),
1191
- ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ';',
1192
- 'before'
1193
- );
1194
-
1195
- // Enqueue Micro-Hydrator orchestrator script
1196
- wp_enqueue_script(
1197
- '${config.textDomain}-hydrator',
1198
- $theme_uri . '/assets/forgewp-hydrator.js',
1199
- array('${config.textDomain}-react-runtime'),
1200
- FORGEWP_THEME_VERSION,
1201
- true
1202
- );
1203
-
1204
- // Integrate dynamic translation dictionary and Polylang / WPML multi-language data
1205
- $i18n_keys = array(
1206
- ${i18nKeysPhp}
1207
- );
1208
- if (function_exists('pll_register_string')) {
1209
- foreach ($i18n_keys as $key) {
1210
- pll_register_string($key, $key, '${config.textDomain}');
1211
- }
1212
- }
1213
- $current_lang = '';
1214
- if (function_exists('pll_current_language')) {
1215
- $current_lang = pll_current_language();
1216
- }
1217
- if (empty($current_lang)) {
1218
- $current_lang = get_locale();
1219
- }
1220
-
1221
- $json_dict = array();
1222
- $translations_file = get_template_directory() . '/translations.json';
1223
- if (file_exists($translations_file)) {
1224
- $json_data = json_decode(file_get_contents($translations_file), true);
1225
- if (is_array($json_data) && isset($json_data[$current_lang])) {
1226
- $json_dict = $json_data[$current_lang];
1227
- }
1228
- }
1229
-
1230
- $translated_dict = array();
1231
- if (is_array($json_dict)) {
1232
- $translated_dict = $json_dict;
1233
- }
1234
- foreach ($i18n_keys as $key) {
1235
- if (!isset($translated_dict[$key])) {
1236
- $translated_dict[$key] = function_exists('pll__') ? pll__($key) : __($key, '${config.textDomain}');
1237
- }
1238
- }
1239
-
1240
- $translations = array();
1241
- $home_urls = array();
1242
- if (function_exists('pll_the_languages')) {
1243
- $langs = pll_the_languages(array('raw' => 1));
1244
- if (is_array($langs)) {
1245
- foreach ($langs as $l) {
1246
- $translations[$l['slug']] = $l['url'];
1247
- if (function_exists('pll_home_url')) {
1248
- $home_urls[$l['slug']] = pll_home_url($l['slug']);
1249
- }
1250
- }
1251
- }
1252
- }
1253
- if (empty($home_urls)) {
1254
- $home_urls[$current_lang] = home_url('/');
1255
- }
1256
-
1257
- wp_add_inline_script(
1258
- '${config.textDomain}-react-runtime',
1259
- 'window.forgeWpTranslations = ' . wp_json_encode(array(
1260
- 'currentLanguage' => $current_lang,
1261
- 'urls' => $translations,
1262
- 'homeUrls' => $home_urls,
1263
- 'translations' => $translated_dict
1264
- ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ';',
1265
- 'before'
1266
- );
1267
-
1268
- $post_custom_fields = array();
1269
- $post_id = get_the_ID();
1270
- if ($post_id > 0) {
1271
- $registered_keys = array(${Array.from(uniqueMetaKeys).map(k => `'${k}'`).join(', ')});
1272
- $rich_text_keys = array(${uniqueRichTextKeys.map(k => `'${k}'`).join(', ')});
1273
- $repeater_fields_map = array(
1274
- ${repeaterFieldsPhp}
1275
- );
1276
- foreach ($registered_keys as $key) {
1277
- if (array_key_exists($key, $repeater_fields_map)) {
1278
- $post_custom_fields[$key] = forgewp_get_repeater_field($key, $repeater_fields_map[$key], $post_id);
1279
- } else {
1280
- $val = null;
1281
- if (function_exists('get_field')) {
1282
- $val = get_field($key, $post_id);
1283
- }
1284
- if ($val === null || $val === false) {
1285
- $val = get_post_meta($post_id, $key, true);
1286
- if (is_string($val) && (strpos($val, '[') === 0 || strpos($val, '{') === 0)) {
1287
- $decoded = json_decode($val, true);
1288
- if (json_last_error() === JSON_ERROR_NONE) {
1289
- $val = $decoded;
1290
- }
1291
- }
1292
- }
1293
- if (in_array($key, $rich_text_keys) && is_string($val)) {
1294
- $val = wpautop($val);
1295
- }
1296
- $post_custom_fields[$key] = $val;
1297
- }
1298
- }
1299
- }
1300
-
1301
- wp_add_inline_script(
1302
- '${config.textDomain}-react-runtime',
1303
- 'if (!window.forgeWpHydration) { window.forgeWpHydration = {}; } window.forgeWpHydration.post = ' . wp_json_encode(array(
1304
- 'id' => $post_id,
1305
- 'customFields' => $post_custom_fields
1306
- ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ';',
1307
- 'before'
1308
- );
1309
- }
1310
-
1311
- function ${config.textDomain.replace(/-/g, '_')}_script_loader_tag($tag, $handle, $src) {
1312
- if (in_array($handle, array('${config.textDomain}-react-runtime', '${config.textDomain}-hydrator'), true)) {
1313
- $tag = preg_replace_callback('/(<script\\b[^>]*src=[^>]*>)/i', function($matches) {
1314
- $script_open = $matches[1];
1315
- $script_open = preg_replace('/\\stype\\s*=\\s*([\\\'"])[^\\\'"]*\\1/i', '', $script_open);
1316
- $script_open = preg_replace('/<script\\b/i', '<script type="module"', $script_open);
1317
- return $script_open;
1318
- }, $tag, 1);
1319
- }
1320
- return $tag;
1321
- }
1322
- add_filter('script_loader_tag', '${config.textDomain.replace(/-/g, '_')}_script_loader_tag', 10, 3);
1323
- `;
1324
- }
1325
-
1326
- // ── Tier 2: Native Post Meta Registrations ──
1327
- let nativeMetaRegisters = '';
1328
- if (uniqueMetaKeys.size > 0) {
1329
- const metaArray = Array.from(uniqueMetaKeys);
1330
-
1331
- // Convert postTypes array into PHP array declaration
1332
- const ptListStr = postTypes.length > 0 ? postTypes.map(pt => `'${pt}'`).join(', ') : '';
1333
- const allPtExpr = ptListStr ? `array_merge(array('post', 'page'), array(${ptListStr}))` : `array('post', 'page')`;
1334
-
1335
- nativeMetaRegisters = `
1336
- /**
1337
- * Register native post meta fields for all templates (Tier 2 Structured Content).
1338
- */
1339
- function forgewp_register_custom_post_meta(): void {
1340
- $post_types = ${allPtExpr};
1341
- foreach ($post_types as $pt) {
1342
- ${metaArray.filter(key => !metaKeysToSkip.has(key)).map(key => {
1343
- const phpType = metaKeyTypes[key];
1344
- return ` register_post_meta($pt, '${key}', array(
1345
- 'show_in_rest' => true,
1346
- 'single' => true,
1347
- 'type' => '${phpType}',
1348
- ));`;
1349
- }).join('\n')}
1350
- }
1351
- }
1352
- add_action('init', 'forgewp_register_custom_post_meta');
1353
- `;
1354
- }
1355
-
1356
- // ── Tier 3: Advanced Custom Fields (ACF) local field groups ──
1357
- let acfFieldGroups = '';
1358
- if (Object.keys(schemas).length > 0 || registeredTaxonomies.length > 0) {
1359
- const groups = [];
1360
- for (const [templateSlug, schema] of Object.entries(schemas)) {
1361
- const groupKey = `group_${templateSlug.replace(/-/g, '_')}`;
1362
- const groupTitle = templateSlug.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ') + ' Content';
1363
-
1364
- let fieldsPhp = ' $fields = array();\n';
1365
- for (const [key, field] of Object.entries(schema)) {
1366
- fieldsPhp += generateDynamicAcfFieldPhp(key, field);
1367
- }
1368
-
1369
- let locationRule = '';
1370
- if (templateSlug === 'front-page') {
1371
- locationRule = `array(
1372
- array(
1373
- array(
1374
- 'param' => 'page_type',
1375
- 'operator' => '==',
1376
- 'value' => 'front_page',
1377
- ),
1378
- ),
1379
- )`;
1380
- } else if (templateSlug.startsWith('single-')) {
1381
- let postType = templateSlug.replace('single-', '');
1382
- if (postType.endsWith('-page')) {
1383
- postType = postType.slice(0, -5);
1384
- }
1385
- locationRule = `array(
1386
- array(
1387
- array(
1388
- 'param' => 'post_type',
1389
- 'operator' => '==',
1390
- 'value' => '${postType}',
1391
- ),
1392
- ),
1393
- )`;
1394
- } else {
1395
- const pageTemplateName = `page-${templateSlug}.php`;
1396
- locationRule = `array(
1397
- array(
1398
- array(
1399
- 'param' => 'page_template',
1400
- 'operator' => '==',
1401
- 'value' => '${pageTemplateName}',
1402
- ),
1403
- ),
1404
- )`;
1405
- }
1406
-
1407
- groups.push(` ${fieldsPhp}
1408
- acf_add_local_field_group(array(
1409
- 'key' => '${groupKey}',
1410
- 'title' => '${groupTitle}',
1411
- 'fields' => $fields,
1412
- 'location' => ${locationRule},
1413
- 'menu_order' => 0,
1414
- 'position' => 'normal',
1415
- 'style' => 'default',
1416
- 'label_placement' => 'top',
1417
- 'instruction_placement' => 'label',
1418
- 'hide_on_screen' => '',
1419
- 'active' => true,
1420
- 'description' => 'Colocated React structured content fields managed by ForgeWP.',
1421
- 'show_in_rest' => true,
1422
- ));`);
1423
- }
1424
-
1425
- // Custom fields for custom taxonomies (like destination countries)
1426
- for (const tax of registeredTaxonomies) {
1427
- const taxGroupKey = `group_taxonomy_${tax}`;
1428
- const taxGroupTitle = tax.split(/[_-]/).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ') + ' Settings';
1429
- groups.push(` // Custom fields for taxonomy: ${tax}
1430
- acf_add_local_field_group(array(
1431
- 'key' => '${taxGroupKey}',
1432
- 'title' => '${taxGroupTitle}',
1433
- 'fields' => array(
1434
- array(
1435
- 'key' => 'field_${tax}_featured_image',
1436
- 'label' => 'Featured Image',
1437
- 'name' => 'featured_image',
1438
- 'type' => 'image',
1439
- 'instructions' => 'Set the cover/featured image for this term.',
1440
- 'required' => 0,
1441
- 'conditional_logic' => 0,
1442
- 'return_format' => 'url',
1443
- 'preview_size' => 'medium',
1444
- 'library' => 'all',
1445
- ),
1446
- array(
1447
- 'key' => 'field_${tax}_flag',
1448
- 'label' => 'Flag Emoji',
1449
- 'name' => 'flag',
1450
- 'type' => 'text',
1451
- 'instructions' => 'Set the flag emoji or brief code for this term (e.g. 🇩🇪 or DE).',
1452
- 'required' => 0,
1453
- 'conditional_logic' => 0,
1454
- 'default_value' => '🌍',
1455
- ),
1456
- ),
1457
- 'location' => array(
1458
- array(
1459
- array(
1460
- 'param' => 'taxonomy',
1461
- 'operator' => '==',
1462
- 'value' => '${tax}',
1463
- ),
1464
- ),
1465
- ),
1466
- 'menu_order' => 0,
1467
- 'position' => 'normal',
1468
- 'style' => 'default',
1469
- 'label_placement' => 'top',
1470
- 'instruction_placement' => 'label',
1471
- 'hide_on_screen' => '',
1472
- 'active' => true,
1473
- 'show_in_rest' => true,
1474
- ));`);
1475
- }
1476
-
1477
- acfFieldGroups = `
1478
- /**
1479
- * Register Advanced Custom Fields (ACF) local field groups (Tier 3 Interoperability Presentation).
1480
- */
1481
- function forgewp_register_acf_field_groups(): void {
1482
- if ( ! function_exists('acf_add_local_field_group') ) {
1483
- return;
1484
- }
1485
-
1486
- ${groups.join('\n\n')}
1487
- }
1488
- add_action('acf/init', 'forgewp_register_acf_field_groups');
1489
- `;
1490
- }
1491
-
1492
- let queryEndpointsPhp = '';
1493
- if (queries && queries.length > 0) {
1494
- queryEndpointsPhp += `\n\n/**\n * ── Compiled REST Query Endpoints (Milestone 2) ──\n */\n`;
1495
- queryEndpointsPhp += `
1496
- if (!function_exists('forgewp_format_rest_post')) {
1497
- function forgewp_format_rest_post(\$post) {
1498
- \$id = \$post->ID;
1499
- \$title = get_the_title(\$post);
1500
- \$excerpt = get_the_excerpt(\$post);
1501
-
1502
- \$content = apply_filters('the_content', \$post->post_content);
1503
- \$date = get_the_date('', \$post);
1504
- \$author = get_the_author_meta('display_name', \$post->post_author);
1505
-
1506
- \$featured_image = 'https://picsum.photos/seed/forgewp/1200/630';
1507
- if (has_post_thumbnail(\$post)) {
1508
- \$thumbnail_url = get_the_post_thumbnail_url(\$post, 'full');
1509
- if (\$thumbnail_url) {
1510
- \$featured_image = \$thumbnail_url;
1511
- }
1512
- }
1513
-
1514
- \$permalink = get_permalink(\$post);
1515
-
1516
- \$custom_fields = array();
1517
- \$meta = get_post_meta(\$id);
1518
- if (is_array(\$meta)) {
1519
- foreach (\$meta as \$key => \$values) {
1520
- \$val = isset(\$values[0]) ? maybe_unserialize(\$values[0]) : '';
1521
- \$custom_fields[\$key] = \$val;
1522
- }
1523
- }
1524
-
1525
- if (function_exists('get_fields')) {
1526
- \$acf_fields = get_fields(\$id);
1527
- if (is_array(\$acf_fields)) {
1528
- \$custom_fields = array_merge(\$custom_fields, \$acf_fields);
1529
- }
1530
- }
1531
-
1532
- \$terms_data = array();
1533
- \$taxonomies = get_object_taxonomies(\$post->post_type);
1534
- if (is_array(\$taxonomies)) {
1535
- foreach (\$taxonomies as \$taxonomy) {
1536
- \$terms = get_the_terms(\$post, \$taxonomy);
1537
- if (is_array(\$terms)) {
1538
- \$terms_data[\$taxonomy] = array();
1539
- foreach (\$terms as \$t) {
1540
- \$terms_data[\$taxonomy][] = array(
1541
- 'id' => \$t->term_id,
1542
- 'slug' => \$t->slug,
1543
- 'name' => html_entity_decode(\$t->name, ENT_QUOTES, 'UTF-8'),
1544
- );
1545
- }
1546
- }
1547
- }
1548
- }
1549
-
1550
- return array(
1551
- 'ID' => \$id,
1552
- 'title' => \$title,
1553
- 'excerpt' => \$excerpt,
1554
- 'content' => \$content,
1555
- 'date' => \$date,
1556
- 'author' => \$author,
1557
- 'featuredImage' => \$featured_image,
1558
- 'permalink' => \$permalink,
1559
- 'customFields' => \$custom_fields,
1560
- '_terms' => \$terms_data,
1561
- 'post_type' => \$post->post_type,
1562
- );
1563
- }
1564
- }
1565
- `;
1566
-
1567
- queryEndpointsPhp += `
1568
- add_action('rest_api_init', function() {`;
1569
- for (const q of queries) {
1570
- const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1571
- const querySlug = 'query-' + cleanId;
1572
- const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
1573
- queryEndpointsPhp += `
1574
- register_rest_route('forgewp/v1', '/${querySlug}', array(
1575
- 'methods' => 'GET',
1576
- 'callback' => '${callbackName}',
1577
- 'permission_callback' => '__return_true',
1578
- ));`;
1579
- }
1580
- queryEndpointsPhp += `
1581
- });
1582
- `;
1583
-
1584
- for (const q of queries) {
1585
- const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1586
- const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
1587
- const phpArgs = generatePhpArgs(q);
1588
-
1589
- queryEndpointsPhp += `
1590
- function ${callbackName}(WP_REST_Request \$request) {
1591
- \$paged = \$request->get_param('page') ? intval(\$request->get_param('page')) : 1;
1592
- \$s = \$request->get_param('search');
1593
- if (empty(\$s)) {
1594
- \$s = \$request->get_param('s');
1595
- }
1596
-
1597
- ${phpArgs}
1598
-
1599
- if (!empty(\$s)) {
1600
- \$args['s'] = sanitize_text_field(\$s);
1601
- }
1602
-
1603
- \$lang = \$request->get_param('lang');
1604
- if (!empty(\$lang)) {
1605
- \$args['lang'] = sanitize_text_field(\$lang);
1606
- }
1607
-
1608
- \$query = new WP_Query(\$args);
1609
- \$posts = array();
1610
- if (\$query->have_posts()) {
1611
- while (\$query->have_posts()) {
1612
- \$query->the_post();
1613
- \$posts[] = forgewp_format_rest_post(\$query->post);
1614
- }
1615
- wp_reset_postdata();
1616
- }
1617
-
1618
- return new WP_REST_Response(array(
1619
- 'posts' => \$posts,
1620
- 'total' => intval(\$query->found_posts),
1621
- 'totalPages' => intval(\$query->max_num_pages),
1622
- ), 200);
1623
- }
1624
- `;
1625
- }
1626
- }
1627
-
1628
- return `<?php
1629
- /**
1630
- * ${config.name} — generated by ForgeWP
1631
- *
1632
- * @package ${config.textDomain}
1633
- */
1634
-
1635
- if (! defined('ABSPATH')) {
1636
- exit;
1637
- }
1638
-
1639
- define('FORGEWP_THEME_VERSION', '${version}');
1640
-
1641
- /**
1642
- * Helper to fetch any repeater field, bypassing ACF internal formatting if needed.
1643
- */
1644
- function forgewp_get_repeater_field($meta_key, $sub_field_keys, $post_id = null) {
1645
- if (!$post_id) {
1646
- $post_id = get_the_ID();
1647
- }
1648
- if (!$post_id) {
1649
- return array();
1650
- }
1651
-
1652
- $rows = array();
1653
-
1654
- // 1. Try get_field first
1655
- if (function_exists('get_field')) {
1656
- $val = get_field($meta_key, $post_id);
1657
- if (is_array($val) && !empty($val)) {
1658
- $rows = $val;
1659
- }
1660
- }
1661
-
1662
- // 2. Direct DB query using ACF structure
1663
- if (empty($rows)) {
1664
- $count = get_post_meta($post_id, $meta_key, true);
1665
- if (is_numeric($count) && intval($count) > 0) {
1666
- $count = intval($count);
1667
- for ($i = 0; $i < $count; $i++) {
1668
- $row = array();
1669
- foreach ($sub_field_keys as $sub_key) {
1670
- $sub_val = get_post_meta($post_id, "{$meta_key}_{$i}_{$sub_key}", true);
1671
- if (is_string($sub_val) && (strpos($sub_val, '[') === 0 || strpos($sub_val, '{') === 0)) {
1672
- $decoded = json_decode($sub_val, true);
1673
- if (is_array($decoded)) {
1674
- $sub_val = $decoded;
1675
- }
1676
- }
1677
- $row[$sub_key] = $sub_val;
1678
- }
1679
- $rows[] = $row;
1680
- }
1681
- }
1682
- }
1683
-
1684
- // 3. Fallback to json_fallback
1685
- if (empty($rows)) {
1686
- $fallback = get_post_meta($post_id, "{$meta_key}_json_fallback", true);
1687
- if (is_string($fallback) && !empty($fallback)) {
1688
- $decoded = json_decode($fallback, true);
1689
- if (is_array($decoded)) {
1690
- $rows = $decoded;
1691
- }
1692
- }
1693
- }
1694
-
1695
- // 4. Raw JSON fallback
1696
- if (empty($rows)) {
1697
- $raw_meta = get_post_meta($post_id, $meta_key, true);
1698
- if (is_string($raw_meta) && !empty($raw_meta)) {
1699
- $decoded = json_decode($raw_meta, true);
1700
- if (is_array($decoded)) {
1701
- $rows = $decoded;
1702
- }
1703
- }
1704
- }
1705
-
1706
- // Normalize rows to resolve image arrays/IDs to URLs
1707
- if (is_array($rows)) {
1708
- foreach ($rows as $index => $row) {
1709
- if (is_array($row)) {
1710
- foreach ($row as $sub_key => $sub_val) {
1711
- if (is_string($sub_val) && (strpos($sub_val, '[') === 0 || strpos($sub_val, '{') === 0)) {
1712
- $decoded = json_decode($sub_val, true);
1713
- if (is_array($decoded)) {
1714
- $sub_val = $decoded;
1715
- }
1716
- }
1717
-
1718
- if (is_array($sub_val) && isset($sub_val['url'])) {
1719
- $sub_val = $sub_val['url'];
1720
- } elseif (is_numeric($sub_val) && intval($sub_val) > 0 && get_post_type(intval($sub_val)) === 'attachment') {
1721
- $url = wp_get_attachment_image_url(intval($sub_val), 'full');
1722
- if ($url) {
1723
- $sub_val = $url;
1724
- }
1725
- }
1726
-
1727
- $rows[$index][$sub_key] = $sub_val;
1728
- }
1729
- }
1730
- }
1731
- }
1732
-
1733
- return is_array($rows) ? $rows : array();
1734
- }
1735
-
1736
- /**
1737
- * Helper to fetch and format page/post meta fields, resolving ACF formatting and attachments.
1738
- */
1739
- function forgewp_get_meta_value($key, $default_val = '', $is_rich_text = false) {
1740
- $post_id = get_the_ID();
1741
- if (!$post_id) {
1742
- return $default_val;
1743
- }
1744
-
1745
- $val = null;
1746
-
1747
- // 1. Try get_field first if ACF is active
1748
- if (function_exists('get_field')) {
1749
- $val = get_field($key, $post_id);
1750
- }
1751
-
1752
- // 2. Direct get_post_meta fallback
1753
- if ($val === null || $val === false) {
1754
- $val = get_post_meta($post_id, $key, true);
1755
- }
1756
-
1757
- // 3. Fallback to default if empty
1758
- if ($val === null || $val === false || $val === '') {
1759
- return $default_val;
1760
- }
1761
-
1762
- // 4. Resolve Image Arrays / Objects (ACF formats)
1763
- if (is_array($val) && isset($val['url'])) {
1764
- $val = $val['url'];
1765
- }
1766
- // 5. Resolve Attachment IDs to URLs
1767
- elseif (is_numeric($val) && intval($val) > 0 && get_post_type(intval($val)) === 'attachment') {
1768
- $url = wp_get_attachment_image_url(intval($val), 'full');
1769
- if ($url) {
1770
- $val = $url;
1771
- }
1772
- }
1773
-
1774
- // 6. Format and escape
1775
- if ($is_rich_text) {
1776
- return wpautop($val);
1777
- } else {
1778
- return esc_html($val);
1779
- }
1780
- }
1781
-
1782
- /**
1783
- * Resolves the menu ID for a location and language, using WordPress nav menu locations.
1784
- */
1785
- function forgewp_get_menu_id_for_lang($location, $lang = '') {
1786
- $locations = get_nav_menu_locations();
1787
-
1788
- if (empty($locations) || !is_array($locations)) {
1789
- return null;
1790
- }
1791
-
1792
- // 1. Try to find the language-specific location key (e.g. primary___de)
1793
- if (!empty($lang)) {
1794
- $lang_key = $location . '___' . $lang;
1795
- if (isset($locations[$lang_key])) {
1796
- return $locations[$lang_key];
1797
- }
1798
- }
1799
-
1800
- // 2. Try to find the base location key (e.g. primary)
1801
- if (isset($locations[$location])) {
1802
- return $locations[$location];
1803
- }
1804
-
1805
- // 3. Fallback to any matching key in the locations array
1806
- foreach ($locations as $key => $val) {
1807
- if ($key === $location || strpos($key, $location . '___') === 0) {
1808
- return $val;
1809
- }
1810
- }
1811
-
1812
- return null;
1813
- }
1814
-
1815
- /**
1816
- * Enqueue compiled theme assets.
1817
- */
1818
- function forgewp_enqueue_assets(): void {
1819
- $theme_uri = get_template_directory_uri();
1820
- $css_path = get_template_directory() . '/assets/${css}';
1821
- ${fontsEnqueue}
1822
-
1823
- if (file_exists($css_path)) {
1824
- wp_enqueue_style(
1825
- '${config.textDomain}-app',
1826
- $theme_uri . '/assets/${css}',
1827
- array(),
1828
- FORGEWP_THEME_VERSION
1829
- );
1830
- }
1831
- ${hydrationEnqueue}
1832
-
1833
-
1834
- }
1835
- add_action('wp_enqueue_scripts', 'forgewp_enqueue_assets');
1836
-
1837
- /**
1838
- * Theme supports.
1839
- */
1840
- function forgewp_theme_setup(): void {
1841
- add_theme_support('title-tag');
1842
- add_theme_support('post-thumbnails');
1843
- add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script'));
1844
- ${wpBlockStylesLine} add_theme_support('editor-styles');
1845
-
1846
- // Load compiled theme stylesheet inside Gutenberg Block Editor
1847
- add_editor_style('assets/${css}');
1848
- ${registerMenusPhp}
1849
- }
1850
- add_action('after_setup_theme', 'forgewp_theme_setup');
1851
- ${preconnectFilter}${blocksRegistration}${cptRegistration}${autoCreationPhp}${nativeMetaRegisters}${acfFieldGroups}
1852
-
1853
- /**
1854
- * Resolves the active template head HTML file path dynamically.
1855
- */
1856
- function forgewp_resolve_head_target() {
1857
- $dir = get_template_directory() . '/forgewp-static';
1858
-
1859
- // 1. Custom Page Template
1860
- $template_slug = get_page_template_slug();
1861
- if ($template_slug) {
1862
- $clean_slug = str_replace(array('page-', '.php'), '', $template_slug);
1863
- $target = "{$dir}/template-{$clean_slug}-head.html";
1864
- if (file_exists($target)) {
1865
- return $target;
1866
- }
1867
- }
1868
-
1869
- // 2. Singular Custom Post Type / Post / Page
1870
- if (is_singular()) {
1871
- $post_type = get_post_type();
1872
- $target = "{$dir}/single-{$post_type}-head.html";
1873
- if (file_exists($target)) {
1874
- return $target;
1875
- }
1876
- $target = "{$dir}/single-head.html";
1877
- if (file_exists($target)) {
1878
- return $target;
1879
- }
1880
- }
1881
-
1882
- // 3. Taxonomy Archive
1883
- if (is_tax()) {
1884
- $tax = get_query_var('taxonomy');
1885
- $target = "{$dir}/taxonomy-{$tax}-head.html";
1886
- if (file_exists($target)) {
1887
- return $target;
1888
- }
1889
- $target = "{$dir}/taxonomy-head.html";
1890
- if (file_exists($target)) {
1891
- return $target;
1892
- }
1893
- }
1894
-
1895
- // 4. Post Type Archive
1896
- if (is_post_type_archive()) {
1897
- $post_type = get_query_var('post_type');
1898
- $target = "{$dir}/archive-{$post_type}-head.html";
1899
- if (file_exists($target)) {
1900
- return $target;
1901
- }
1902
- }
1903
-
1904
- // 5. General Archive / Category / Tag
1905
- if (is_archive()) {
1906
- $target = "{$dir}/archive-head.html";
1907
- if (file_exists($target)) {
1908
- return $target;
1909
- }
1910
- }
1911
-
1912
- // 6. Default Head
1913
- return "{$dir}/head.html";
1914
- }
1915
-
1916
- /**
1917
- * Custom document title filter for ForgeWP.
1918
- * Maps title enqueued via <WpHead /> in React to WordPress.
1919
- */
1920
- function forgewp_custom_document_title( $title ) {
1921
- if ( defined('WPSEO_VERSION') || class_exists('RankMath') || class_exists('All_in_One_SEO_Pack') || defined('AIOSEO_VERSION') ) {
1922
- return $title;
1923
- }
1924
- $target = forgewp_resolve_head_target();
1925
- if ( file_exists( $target ) ) {
1926
- ob_start();
1927
- include $target;
1928
- $content = ob_get_clean();
1929
- if ( preg_match( '/<title>(.*?)<\\/title>/is', $content, $matches ) ) {
1930
- return html_entity_decode( trim( $matches[1] ), ENT_QUOTES, 'UTF-8' );
1931
- }
1932
- }
1933
- return $title;
1934
- }
1935
- add_filter( 'pre_get_document_title', 'forgewp_custom_document_title', 999 );
1936
- ${seoPluginsPhp}
1937
-
1938
- /**
1939
- * Disable WordPress legacy emoji conversion to match native client-side rendering.
1940
- */
1941
- function forgewp_disable_emojis(): void {
1942
- remove_action('wp_head', 'print_emoji_detection_script', 7);
1943
- remove_action('admin_print_scripts', 'print_emoji_detection_script');
1944
- remove_action('wp_print_styles', 'print_emoji_styles');
1945
- remove_action('admin_print_styles', 'print_emoji_styles');
1946
- remove_filter('the_content_feed', 'wp_staticize_emoji');
1947
- remove_filter('comment_text_rss', 'wp_staticize_emoji');
1948
- remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
1949
- add_filter('tiny_mce_plugins', 'forgewp_disable_emojis_tinymce');
1950
- add_filter('wp_resource_hints', 'forgewp_disable_emojis_remove_dns_prefetch', 10, 2);
1951
- }
1952
- add_action('init', 'forgewp_disable_emojis');
1953
-
1954
- function forgewp_disable_emojis_tinymce($plugins) {
1955
- return is_array($plugins) ? array_diff($plugins, array('wpemoji')) : array();
1956
- }
1957
-
1958
- function forgewp_disable_emojis_remove_dns_prefetch($urls, $relation_type) {
1959
- if ('dns-prefetch' === $relation_type) {
1960
- $emoji_svg_url = apply_filters('emoji_svg_url', 'https://s.w.org/images/core/emoji/2.2.1/svg/');
1961
- $urls = array_diff($urls, array($emoji_svg_url));
1962
- }
1963
- return $urls;
1964
- }
1965
-
1966
- /**
1967
- * Isomorphic static translation bridge for ForgeWP.
1968
- * Hooks into WordPress gettext to translate server-side static strings
1969
- * using translations.json and the active Polylang language.
1970
- */
1971
- function forgewp_gettext_translation_bridge($translated, $text, $domain) {
1972
- if ($domain === '${config.textDomain}') {
1973
- static $translations = null;
1974
- if ($translations === null) {
1975
- $file = get_template_directory() . '/translations.json';
1976
- if (file_exists($file)) {
1977
- $translations = json_decode(file_get_contents($file), true);
1978
- } else {
1979
- $translations = array();
1980
- }
1981
- }
1982
- $type = '';
1983
- if (function_exists('pll_current_language')) {
1984
- $type = pll_current_language();
1985
- }
1986
- if (empty($type)) {
1987
- $type = get_locale();
1988
- }
1989
- $type = substr($type, 0, 2);
1990
- if (is_array($translations) && isset($translations[$type][$text])) {
1991
- return $translations[$type][$text];
1992
- }
1993
- }
1994
- return $translated;
1995
- }
1996
- add_filter('gettext', 'forgewp_gettext_translation_bridge', 10, 3);
1997
- add_filter('ngettext', 'forgewp_gettext_translation_bridge', 10, 3);
1998
-
1999
- /**
2000
- * Dynamic SVG theme icon rendering callback.
2001
- * Maps dynamic icon slugs to inline SVGs from Lucide or custom developer uploads.
2002
- */
2003
- function forgewp_render_theme_icon($icon_slug, $class_name = '', $provider = 'lucide') {
2004
- $svgs = array(
2005
- 'award' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-award"><path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526"></path><circle cx="12" cy="8" r="6"></circle></svg>',
2006
- 'shield' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shield"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"></path></svg>',
2007
- 'globe' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-globe"><circle cx="12" cy="12" r="10"></circle><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path><path d="M2 12h20"></path></svg>',
2008
- 'users' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-users"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M22 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>',
2009
- );
2010
-
2011
- $custom_svgs = get_option(\'forgewp_custom_icons\', array());
2012
- if ($provider === \'custom\' && isset($custom_svgs[$icon_slug])) {
2013
- $svg = $custom_svgs[$icon_slug];
2014
- } else {
2015
- $svg = isset($svgs[$icon_slug]) ? $svgs[$icon_slug] : '';
2016
- }
2017
-
2018
- if (!empty($svg)) {
2019
- if (!empty($class_name)) {
2020
- $svg = str_replace('<svg ', '<svg class="' . esc_attr($class_name) . '" ', $svg);
2021
- }
2022
- echo $svg;
2023
- }
2024
- }
2025
- ${faviconPhp}${sitemapsPhp}${queryEndpointsPhp}
2026
-
2027
- /**
2028
- * Prevent TinyMCE Classic Editor auto-resize height expansion feedback loop.
2029
- */
2030
- function forgewp_disable_editor_autoresize($init_array) {
2031
- if (isset($init_array['plugins'])) {
2032
- $plugins = explode(',', $init_array['plugins']);
2033
- $key = array_search('wpautoresize', $plugins);
2034
- if ($key !== false) {
2035
- unset($plugins[$key]);
2036
- $init_array['plugins'] = implode(',', $plugins);
2037
- }
2038
- }
2039
- return $init_array;
2040
- }
2041
- add_filter('tiny_mce_before_init', 'forgewp_disable_editor_autoresize');
2042
- `;
2043
- }
2044
-