-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
737 lines (622 loc) · 22.4 KB
/
functions.php
File metadata and controls
737 lines (622 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
<?php
/**
* Theme setup.
*/
function clientkit_setup() {
add_theme_support( 'title-tag' );
register_nav_menus(
array(
'primary' => __( 'Primary Menu', 'clientkit' ),
)
);
add_theme_support(
'html5',
array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
)
);
add_theme_support( 'custom-logo' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'align-wide' );
add_theme_support( 'wp-block-styles' );
add_theme_support( 'editor-styles' );
// Prefer manifest path for editor CSS, fallback to non-hashed
if (!function_exists('client_vite_manifest_relpath')) {
function client_vite_manifest_path() {
$base = get_stylesheet_directory() . '/build';
$paths = [ $base . '/manifest.json', $base . '/.vite/manifest.json' ];
foreach ($paths as $p) {
if (file_exists($p)) return $p;
}
return $paths[0];
}
function client_vite_manifest() {
static $manifest = null;
if ($manifest !== null) return $manifest;
$path = client_vite_manifest_path();
if (!file_exists($path)) return $manifest = null;
$data = json_decode(file_get_contents($path), true);
return $manifest = (is_array($data) ? $data : null);
}
function client_vite_manifest_relpath($key) {
$manifest = client_vite_manifest();
if (!$manifest) return null;
if (isset($manifest[$key]['file'])) {
return 'build/' . ltrim($manifest[$key]['file'], '/');
}
return null;
}
function client_vite_manifest_uri($key) {
$manifest = client_vite_manifest();
if (!$manifest) return null;
if (isset($manifest[$key]['file'])) {
return get_stylesheet_directory_uri() . '/build/' . ltrim($manifest[$key]['file'], '/');
}
return null;
}
}
$__editor_rel = client_vite_manifest_relpath('resources/css/editor-style.css');
add_editor_style( $__editor_rel ?: 'build/css/editor-style.css' );
}
add_action( 'after_setup_theme', 'clientkit_setup' );
// Save JSON to theme / perf
add_filter('acf/settings/save_json', function ($path) {
return get_stylesheet_directory() . '/acf-json';
});
// Load JSON from theme (in addition to DB)
add_filter('acf/settings/load_json', function ($paths) {
array_unshift($paths, get_stylesheet_directory() . '/acf-json');
return $paths;
});
function client_enqueue_scripts() {
$theme = wp_get_theme();
// CSS via manifest
$css_url = function_exists('client_vite_manifest_uri') ? client_vite_manifest_uri('resources/css/app.css') : null;
if ($css_url) {
wp_enqueue_style('client-app', $css_url, array(), null);
} else {
// Fallback to non-hashed path if manifest missing
$css_path = get_stylesheet_directory() . '/build/css/app.css';
if (file_exists($css_path)) {
$ver = wp_get_environment_type() === 'production' ? $theme->get('Version') : date('YmdHis', filemtime($css_path));
wp_enqueue_style('client-app', get_stylesheet_directory_uri() . '/build/css/app.css', array(), $ver);
}
}
// JS via manifest
$js_url = function_exists('client_vite_manifest_uri') ? client_vite_manifest_uri('resources/js/app.js') : null;
if ($js_url) {
wp_enqueue_script('client-app', $js_url, array(), null, true);
if (function_exists('wp_script_add_data')) wp_script_add_data('client-app', 'type', 'module');
} else {
$js_path = get_stylesheet_directory() . '/build/js/app.js';
if (file_exists($js_path)) {
$ver = wp_get_environment_type() === 'production' ? $theme->get('Version') : date('YmdHis', filemtime($js_path));
wp_enqueue_script('client-app', get_stylesheet_directory_uri() . '/build/js/app.js', array(), $ver, true);
}
}
// Editor CSS in admin via manifest
if (is_admin()) {
$editor_url = function_exists('client_vite_manifest_uri') ? client_vite_manifest_uri('resources/css/editor-style.css') : null;
if ($editor_url) {
wp_enqueue_style('client-editor', $editor_url, array(), null);
} else {
$editor_css_path = get_stylesheet_directory() . '/build/css/editor-style.css';
if (file_exists($editor_css_path)) {
$ver = wp_get_environment_type() === 'production' ? $theme->get('Version') : date('YmdHis', filemtime($editor_css_path));
wp_enqueue_style('client-editor', get_stylesheet_directory_uri() . '/build/css/editor-style.css', array(), $ver);
}
}
}
}
add_action( 'wp_enqueue_scripts', 'client_enqueue_scripts' );
// Manifest helpers declared above in setup section
/**
* Get asset path.
*
* @param string $path Path to asset.
*
* @return string
*/
function clientkit_asset( $path ) {
// This function is kept for backward compatibility
// but the main asset loading is now handled in client_enqueue_scripts
if ( wp_get_environment_type() === 'production' ) {
return get_stylesheet_directory_uri() . '/' . $path;
}
return add_query_arg( 'time', time(), get_stylesheet_directory_uri() . '/' . $path );
}
/**
* Adds option 'li_class' to 'wp_nav_menu'.
*
* @param string $classes String of classes.
* @param mixed $item The current item.
* @param WP_Term $args Holds the nav menu arguments.
*
* @return array
*/
function clientkit_nav_menu_add_li_class( $classes, $item, $args, $depth ) {
if ( isset( $args->li_class ) ) {
$classes[] = $args->li_class;
}
if ( isset( $args->{"li_class_$depth"} ) ) {
$classes[] = $args->{"li_class_$depth"};
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'clientkit_nav_menu_add_li_class', 10, 4 );
/**
* Adds option 'submenu_class' to 'wp_nav_menu'.
*
* @param string $classes String of classes.
* @param mixed $item The current item.
* @param WP_Term $args Holds the nav menu arguments.
*
* @return array
*/
function clientkit_nav_menu_add_submenu_class( $classes, $args, $depth ) {
if ( isset( $args->submenu_class ) ) {
$classes[] = $args->submenu_class;
}
if ( isset( $args->{"submenu_class_$depth"} ) ) {
$classes[] = $args->{"submenu_class_$depth"};
}
return $classes;
}
add_filter( 'nav_menu_submenu_css_class', 'clientkit_nav_menu_add_submenu_class', 10, 3 );
/**
* ============================================
* CLIENT STATIC COMPILATION SYSTEM
* Compiles ACF modules to static HTML on save
* ============================================
*/
/**
* Check if post should be compiled
*/
function client_should_compile($post_id) {
// Skip autosaves and revisions
if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
return false;
}
// Only compile pages with ACF modules
$post_type = get_post_type($post_id);
if (!in_array($post_type, ['page', 'post'])) {
return false;
}
// Check if post has modules field
if (!have_rows('modules', $post_id)) {
return false;
}
return true;
}
/**
* Build lock management
*/
function client_is_build_locked($post_id) {
return get_transient('client_build_lock_' . $post_id) !== false;
}
function client_set_build_lock($post_id) {
set_transient('client_build_lock_' . $post_id, 1, 60); // 60 second timeout
}
function client_clear_build_lock($post_id) {
delete_transient('client_build_lock_' . $post_id);
}
/**
* Generate dynamic module marker
*/
function client_dynamic_marker($layout, $config) {
$data = [
'layout' => $layout,
'config' => $config
];
return sprintf(
'<div class="client-dyn" data-client="%s"></div>',
esc_attr(base64_encode(json_encode($data)))
);
}
/**
* Compile post modules to static HTML
*/
function client_compile_post($post_id) {
// Guard clauses
if (client_is_build_locked($post_id)) {
return;
}
if (!client_should_compile($post_id)) {
return;
}
// Don't compile during preview
if (is_preview()) {
return;
}
client_set_build_lock($post_id);
try {
$compiled = '';
$stats = ['static' => 0, 'dynamic' => 0, 'start_time' => microtime(true)];
while (have_rows('modules', $post_id)) {
the_row();
$layout = get_row_layout();
$template_file = locate_template("template-parts/module-{$layout}.php");
if (!$template_file) {
continue;
}
// PROBE PHASE - Check if module is dynamic
$GLOBALS['CLIENT_COMPILE_PROBE'] = true;
$GLOBALS['client_module_dynamic'] = false;
$GLOBALS['client_module_config'] = [];
// Include module in probe mode
ob_start();
include($template_file);
ob_end_clean();
$is_dynamic = $GLOBALS['client_module_dynamic'];
$module_config = $GLOBALS['client_module_config'];
unset($GLOBALS['CLIENT_COMPILE_PROBE']);
unset($GLOBALS['client_module_dynamic']);
unset($GLOBALS['client_module_config']);
if ($is_dynamic) {
// Dynamic module - insert marker
$stats['dynamic']++;
$compiled .= "\n" . client_dynamic_marker($layout, $module_config) . "\n";
} else {
// Static module - render and capture HTML
$stats['static']++;
$GLOBALS['CLIENT_MODULE_STATIC'] = true;
ob_start();
include($template_file);
$module_html = ob_get_clean();
unset($GLOBALS['CLIENT_MODULE_STATIC']);
$compiled .= "\n" . $module_html . "\n";
}
}
// Calculate compile time
$compile_time = round(microtime(true) - $stats['start_time'], 3);
// Add debug comment (only in development)
if (wp_get_environment_type() !== 'production') {
$debug_comment = sprintf(
"<!-- client:compiled %s | modules:%d | static:%d | dynamic:%d | time:%ss -->\n",
current_time('Y-m-d H:i:s'),
$stats['static'] + $stats['dynamic'],
$stats['static'],
$stats['dynamic'],
$compile_time
);
$compiled = $debug_comment . $compiled;
}
// Save compiled HTML to post meta
update_post_meta($post_id, '_client_compiled_modules', $compiled);
update_post_meta($post_id, '_client_compiled_time', current_time('mysql'));
update_post_meta($post_id, '_client_compiled_stats', [
'static' => $stats['static'],
'dynamic' => $stats['dynamic'],
'compile_time' => $compile_time
]);
// Log success
if (wp_get_environment_type() !== 'production') {
error_log(sprintf(
'Client: Compiled post #%d - %d static, %d dynamic modules in %ss',
$post_id,
$stats['static'],
$stats['dynamic'],
$compile_time
));
}
} catch (Exception $e) {
error_log('Client compilation error for post #' . $post_id . ': ' . $e->getMessage());
} finally {
client_clear_build_lock($post_id);
}
}
/**
* Hook into ACF save to compile modules
*/
add_action('acf/save_post', 'client_compile_post', 20);
/**
* Clear compiled cache when needed
*/
function client_clear_compiled_cache($post_id) {
delete_post_meta($post_id, '_client_compiled_modules');
delete_post_meta($post_id, '_client_compiled_time');
delete_post_meta($post_id, '_client_compiled_stats');
}
/**
* Helpers for module templates
*/
function client_dynamic($fields = []) {
if (!empty($GLOBALS['CLIENT_COMPILE_PROBE'])) {
$config = [];
foreach ((array) $fields as $fieldName) {
$config[$fieldName] = function_exists('get_sub_field') ? get_sub_field($fieldName) : null;
}
$GLOBALS['client_module_dynamic'] = true;
$GLOBALS['client_module_config'] = $config;
return true;
}
return false;
}
function client_field($name, $default = null) {
if (!empty($GLOBALS['CLIENT_DYNAMIC_RENDER'])) {
return $GLOBALS['client_module_config'][$name] ?? $default;
}
return function_exists('get_sub_field') ? get_sub_field($name) : $default;
}
/**
* Print compiled modules on frontend (new name: client_modules)
*/
/**
* Detect local/dev environment for live rendering convenience
*/
function client_is_local_dev() {
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
if (function_exists('wp_get_environment_type') && wp_get_environment_type() === 'development') {
return true;
}
if (defined('WP_DEBUG') && constant('WP_DEBUG')) {
return true;
}
if ($host) {
$host_no_port = preg_replace('/:\\d+$/', '', $host);
if (preg_match('/(^localhost$|^127\\.0\\.0\\.1$|\\.local$)/', $host_no_port)) {
return true;
}
}
return false;
}
function client_modules($post_id = null) {
if (!$post_id) {
$post_id = get_the_ID();
}
// Local/dev: render live by default
// Overrides:
// - ?live=1 → force compiled (requested semantics)
// - ?live=0 → force live
// Back-compat aliases: client_live=1, client_compiled=1
$live_param = isset($_GET['live']) ? $_GET['live'] : null;
$force_compiled = ($live_param === '1') || (isset($_GET['client_compiled']) && $_GET['client_compiled'] == '1');
$force_live = ($live_param === '0') || (isset($_GET['client_live']) && $_GET['client_live'] == '1');
if (($force_live && !$force_compiled) || (client_is_local_dev() && !$force_compiled)) {
client_print_live_modules($post_id);
return;
}
// In preview mode or if no compiled content exists, render live
if (is_preview() || !get_post_meta($post_id, '_client_compiled_modules', true)) {
client_print_live_modules($post_id);
return;
}
// Get compiled HTML
$compiled = get_post_meta($post_id, '_client_compiled_modules', true);
// Expand dynamic markers
$compiled = preg_replace_callback(
'/<div class="client-dyn" data-client="([^"]+)"><\/div>/',
function($matches) {
$data = json_decode(base64_decode($matches[1]), true);
if (!$data || !isset($data['layout'])) {
return '';
}
$template_file = locate_template("template-parts/module-{$data['layout']}.php");
if (!$template_file) {
return '';
}
// Set up globals for dynamic render
$GLOBALS['CLIENT_DYNAMIC_RENDER'] = true;
$GLOBALS['client_module_config'] = $data['config'] ?? [];
ob_start();
include($template_file);
$output = ob_get_clean();
unset($GLOBALS['CLIENT_DYNAMIC_RENDER']);
unset($GLOBALS['client_module_config']);
return $output;
},
$compiled
);
// Allow final adjustments. We do NOT run the_content by default to avoid wpautop wrapping breaking layout.
// To opt-in globally, add: add_filter('client_compiled_html_use_the_content', '__return_true');
if (apply_filters('client_compiled_html_use_the_content', false, $post_id)) {
$compiled = apply_filters('the_content', $compiled);
} else {
$compiled = apply_filters('client_compiled_html', $compiled, $post_id);
}
echo $compiled;
}
// Backward compatibility: old function name
if (!function_exists('client_print_compiled_modules')) {
function client_print_compiled_modules($post_id = null) {
return client_modules($post_id);
}
}
/**
* Fallback: Print modules live (without compilation)
*/
function client_print_live_modules($post_id = null) {
if (!$post_id) {
$post_id = get_the_ID();
}
if (have_rows('modules', $post_id)) {
while (have_rows('modules', $post_id)) {
the_row();
$layout = get_row_layout();
get_template_part('template-parts/module', $layout);
}
}
}
/**
* Admin notice for compilation status
*/
function client_admin_compilation_status() {
global $post;
if (!$post || !in_array($post->post_type, ['page', 'post'])) {
return;
}
$compiled_time = get_post_meta($post->ID, '_client_compiled_time', true);
$stats = get_post_meta($post->ID, '_client_compiled_stats', true);
if ($compiled_time && $stats) {
echo '<div class="notice notice-success is-dismissible">';
echo '<p><strong>Static Compilation:</strong> ';
echo sprintf(
'Last compiled %s - %d static, %d dynamic modules (%.3fs)',
human_time_diff(strtotime($compiled_time), current_time('timestamp')) . ' ago',
$stats['static'],
$stats['dynamic'],
$stats['compile_time']
);
echo '</p>';
echo '</div>';
}
}
add_action('admin_notices', 'client_admin_compilation_status');
/**
* Admin: Static Compiler Tools (Rebuild All)
*/
function client_admin_tools_menu() {
add_management_page(
'Static Compiler',
'Static Compiler',
'manage_options',
'client-static-compiler',
'client_admin_tools_page'
);
}
add_action('admin_menu', 'client_admin_tools_menu');
/**
* Populate ACF dropdown with Contact Form 7 forms
*/
function client_populate_cf7_forms($field) {
// Only populate for our specific field
if ($field['name'] !== 'contact_form') {
return $field;
}
// Reset choices
$field['choices'] = array();
// Check if WPCF7 is active
if (!class_exists('WPCF7_ContactForm')) {
$field['choices'][''] = 'Contact Form 7 not installed';
return $field;
}
// Get all CF7 forms
$forms = WPCF7_ContactForm::find();
if (empty($forms)) {
$field['choices'][''] = 'No forms found';
return $field;
}
// Populate choices with form ID => Form Title
foreach ($forms as $form) {
$field['choices'][$form->id()] = $form->title();
}
return $field;
}
add_filter('acf/load_field', 'client_populate_cf7_forms');
function client_get_rebuild_queue() {
$queue = get_option('client_rebuild_queue');
if (!is_array($queue)) $queue = [];
return array_values(array_unique(array_map('intval', $queue)));
}
function client_set_rebuild_queue($ids) {
update_option('client_rebuild_queue', array_values(array_unique(array_map('intval', (array)$ids))));
}
function client_clear_rebuild_queue() {
delete_option('client_rebuild_queue');
}
function client_enqueue_all_rebuild() {
$ids = get_posts([
'post_type' => ['page','post'],
'post_status' => 'publish',
'fields' => 'ids',
'posts_per_page' => -1,
]);
// Filter to only those that have modules
$ids_with_modules = [];
foreach ($ids as $id) {
if (have_rows('modules', $id)) {
$ids_with_modules[] = (int)$id;
}
}
client_set_rebuild_queue($ids_with_modules);
}
function client_schedule_rebuild_cron() {
if (!wp_next_scheduled('client_rebuild_batch_event')) {
wp_schedule_single_event(time() + 5, 'client_rebuild_batch_event');
}
}
add_action('client_rebuild_batch_event', 'client_run_rebuild_batch');
function client_run_rebuild_batch() {
$queue = client_get_rebuild_queue();
if (empty($queue)) {
return;
}
$batch_size = 50; // tune as needed
$batch = array_splice($queue, 0, $batch_size);
foreach ($batch as $post_id) {
// Clear and compile fresh
client_clear_compiled_cache($post_id);
client_compile_post($post_id);
}
client_set_rebuild_queue($queue);
if (!empty($queue)) {
// schedule next batch
wp_schedule_single_event(time() + 10, 'client_rebuild_batch_event');
}
}
function client_admin_tools_page() {
if (!current_user_can('manage_options')) return;
$message = '';
if (isset($_POST['client_rebuild_all']) && check_admin_referer('client_rebuild_all')) {
client_enqueue_all_rebuild();
client_schedule_rebuild_cron();
$message = 'Rebuild queued. Batches will run in the background.';
}
if (isset($_POST['client_rebuild_run_batch']) && check_admin_referer('client_rebuild_run_batch')) {
client_run_rebuild_batch();
$message = 'One batch executed.';
}
if (isset($_POST['client_rebuild_cancel']) && check_admin_referer('client_rebuild_cancel')) {
client_clear_rebuild_queue();
$message = 'Rebuild queue cleared.';
}
$queue = client_get_rebuild_queue();
$queued = count($queue);
echo '<div class="wrap">';
echo '<h1>Static Compiler</h1>';
if ($message) echo '<div class="updated notice"><p>' . esc_html($message) . '</p></div>';
echo '<p>Queue size: <strong>' . intval($queued) . '</strong></p>';
echo '<form method="post" style="margin-bottom:12px;">';
wp_nonce_field('client_rebuild_all');
submit_button('Rebuild all pages (enqueue)', 'primary', 'client_rebuild_all', false);
echo '</form>';
echo '<form method="post" style="margin-bottom:12px;">';
wp_nonce_field('client_rebuild_run_batch');
submit_button('Run one batch now', 'secondary', 'client_rebuild_run_batch', false);
echo '</form>';
echo '<form method="post">';
wp_nonce_field('client_rebuild_cancel');
submit_button('Cancel & clear queue', 'delete', 'client_rebuild_cancel', false, ['onclick' => "return confirm('Clear queued rebuilds?')"]);
echo '</form>';
echo '<p class="description">Batches process ~50 pages per run via WP‑Cron. Leave this page or keep browsing; it will continue in the background.</p>';
echo '</div>';
}
/**
* ============================================
* CLIENT MODULE HELPER FUNCTIONS
* Simple helpers for cleaner module code
* ============================================
*/
/**
* Safe content output with proper filtering
*/
function client_content($content, $filter = 'wp_kses_post') {
if (empty($content)) return '';
// Apply content filtering
switch ($filter) {
case 'wp_kses_post':
return wp_kses_post($content);
case 'esc_html':
return esc_html($content);
case 'none':
return $content;
default:
return wp_kses_post($content);
}
}
// Load static badge
require_once get_stylesheet_directory() . '/functions-badge.php';