@forgewp/compiler 0.3.0 → 0.4.1

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