-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathFunctions.php
More file actions
3525 lines (2977 loc) · 150 KB
/
Functions.php
File metadata and controls
3525 lines (2977 loc) · 150 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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if ( !defined('ABSPATH') ){ die(); } //Exit if accessed directly
if ( !trait_exists('Functions') ){
trait Functions {
public $slug_keywords = false; //Start with this false for 404 pages
public $twitter_widget_loaded = false;
public $linkedin_widget_loaded = false;
public $pinterest_pin_widget_loaded = false;
public $current_theme_template;
public $error_query;
public function hooks(){
global $pagenow;
add_action('template_redirect', array($this, 'set_content_width'));
add_action('after_setup_theme', array($this, 'theme_setup'));
add_filter('site_icon_image_sizes', array($this, 'site_icon_sizes'));
add_filter('image_size_names_choose', array($this, 'image_size_human_names'));
add_action('rest_api_init', array($this, 'rest_api_routes'));
add_action('wp_head', array($this, 'add_back_post_feed'));
add_action('init', array($this, 'set_default_timezone'), 1); //WP Health Check does not like this, but date() times break without this
if ( $this->get_option('console_css') && !$this->is_background_request() ){
add_action('wp_head', array($this, 'calling_card'));
}
if ( is_writable(get_template_directory()) ){
if ( !file_exists($this->manifest_json_location(false)) || filemtime($this->manifest_json_location(false)) < (time()-DAY_IN_SECONDS) || $this->is_debug() ){ //If the manifest file does not exist, or last modified time is older than 24 hours re-write it
add_action('init', array($this, 'manifest_json'));
}
}
if ( $this->get_option('service_worker') && is_writable(get_home_path()) ){
if ( file_exists($this->sw_location(false)) ){
add_action('save_post', array($this, 'update_sw_js'));
}
}
add_action('wp_loaded', array($this, 'favicon_cache'));
add_action('after_setup_theme', array($this, 'nav_menu_locations'));
add_filter('nav_menu_link_attributes', array($this, 'add_menu_attributes'), 10, 3);
add_action('admin_init', array($this, 'disable_trackbacks'));
add_action('template_include', array($this, 'define_current_template'), 1000);
add_action('wp_ajax_nebula_twitter_cache', array($this, 'twitter_cache'));
add_action('wp_ajax_nopriv_nebula_twitter_cache', array($this, 'twitter_cache'));
add_filter('get_search_form', array($this, 'search_form'), 100, 1);
add_filter('the_password_form', array($this, 'password_form_simplify'));
add_filter('the_posts', array($this, 'always_get_post_custom'));
add_action('pre_get_posts', array($this, 'redirect_empty_search'));
add_action('template_redirect', array($this, 'redirect_single_search_result'));
add_filter('relevanssi_post_ok', array($this, 'exclude_from_relevanssi'), 10, 2);
if ( !$this->is_background_request() && !$this->is_admin_page() ){
add_action('wp_head', array($this, 'arbitrary_code_head'), 1000);
add_action('nebula_body_open', array($this, 'arbitrary_code_body'), 1000);
add_action('wp_footer', array($this, 'arbitrary_code_footer'), 1000);
add_filter('single_template', array($this, 'single_category_template'));
add_action('wp_head', array($this, 'internal_suggestions'));
add_filter('body_class', array($this, 'body_classes'));
add_filter('post_class', array($this, 'post_classes'));
add_filter('wp_get_attachment_url', array($this, 'wp_get_attachment_url_force_protocol'));
add_filter('embed_oembed_html', array($this, 'oembed_modifiers'), 9999, 4);
}
add_action('wp_ajax_nebula_infinite_load', array($this, 'infinite_load'));
add_action('wp_ajax_nopriv_nebula_infinite_load', array($this, 'infinite_load'));
add_filter('acf/settings/google_api_key', array($this, 'acf_google_api_key')); //ACF hook
if ( is_plugin_active('wordpress-seo/wp-seo.php') ){ //If Yoast is active
add_filter('wpseo_metadesc', array($this, 'meta_description')); //Yoast hook
}
if ( is_user_logged_in() ){
add_filter('wpcf7_verify_nonce', '__return_true'); //Always verify CF7 nonce for logged-in users (this allows for it to detect user data)
}
add_filter('wpcf7_form_elements', array($this, 'cf7_autocomplete_attribute'));
add_filter('wpcf7_special_mail_tags', array($this, 'cf7_custom_special_mail_tags'), 10, 3);
if ( is_plugin_active('contact-form-7/wp-contact-form-7.php') && $this->get_option('store_form_submissions') ){ //If CF7 is installed and active and capturing submission data is enabled
add_action('init', array($this, 'cf7_storage_taxonomies')); //Custom Post Type and Custom Status
add_filter('wpcf7_posted_data', array($this, 'cf7_enhance_data')); //Add more context for CF7 form submissions
add_action('wpcf7_submit', array($this, 'cf7_storage'), 2, 2); //Store CF7 submissions as a CPT (formerly hooked on wpcf7_before_send_mail)
}
if ( $this->is_bypass_cache() ){
if ( !defined('DONOTCACHEPAGE') ){
define('DONOTCACHEPAGE', true); //Tell other plugins not to cache this page
}
add_filter('style_loader_src', array($this, 'add_debug_query_arg'), 500, 1);
add_filter('script_loader_src', array($this, 'add_debug_query_arg'), 500, 1);
add_action('send_headers', array($this, 'clear_site_data'));
add_action('send_headers', 'nocache_headers'); //WP Core function that adds nocache headers
add_action('shutdown', array($this, 'flush_rewrite_on_debug')); //Just on debug, not when auditing
}
}
//Adjust the content width when the full width page template is being used
public function set_content_width(){
$override = apply_filters('pre_nebula_set_content_width', false);
if ( $override !== false ){return $override;}
//$content_width is a global variable used by WordPress for max image upload sizes and media embeds (in pixels).
global $content_width;
//If the content area is 960px wide, set $content_width = 940; so images and videos will not overflow.
if ( !isset($content_width) ){
$content_width = 710;
}
if ( is_page_template('fullwidth.php') ){
$content_width = 1040;
}
}
//Check if the Nebula Companion plugin is installed and active
public function is_companion_active(){
include_once ABSPATH . 'wp-admin/includes/plugin.php'; //Needed to use is_plugin_active() outside of WP admin
if ( is_plugin_active('nebula-companion/nebula-companion.php') || is_plugin_active('Nebula-Companion-main/nebula-companion.php') ){
return true;
}
return false;
}
//Prep custom theme support
public function theme_setup(){
//Additions
add_theme_support('post-thumbnails');
add_theme_support('custom-logo'); //Custom logo support.
add_theme_support('title-tag'); //Title tag support allows WordPress core to create the <title> tag.
//add_theme_support('html5', array('comment-list', 'comment-form', 'search-form', 'gallery', 'caption'));
add_theme_support('automatic-feed-links'); //Add default posts and comments RSS feed links to head
add_theme_support('responsive-embeds');
add_theme_support('wp-block-styles');
add_theme_support('align-wide'); //Wide image alignment
//Custom color palette to Gutenberg editor
add_theme_support('editor-color-palette', array(
array(
'name' => 'Primary',
'slug' => 'primary',
'color' => get_theme_mod('nebula_primary_color', $this->get_color('$primary_color')),
),
array(
'name' => 'Secondary',
'slug' => 'secondary',
'color' => get_theme_mod('nebula_secondary_color', $this->get_color('$secondary_color')),
)
));
add_post_type_support('page', 'excerpt'); //Allow pages to have excerpts too
//Removals
remove_theme_support('custom-background');
remove_theme_support('custom-header');
//Remove capital P core function
remove_filter('the_title', 'capital_P_dangit', 11);
remove_filter('the_content', 'capital_P_dangit', 11);
remove_filter('comment_text', 'capital_P_dangit', 31);
//Head information
remove_action('wp_head', 'rsd_link'); //Remove the link to the Really Simple Discovery service endpoint and EditURI link (third-party editing APIs)
remove_action('wp_head', 'wp_generator'); //Removes the WordPress XHTML Generator meta tag and WP version
remove_action('wp_head', 'wp_shortlink_wp_head'); //Removes the shortlink tag in the head
remove_action('wp_head', 'feed_links', 2); //Remove the links to the general feeds: Post and Comment Feed
remove_action('wp_head', 'wlwmanifest_link'); //Remove the link to the Windows Live Writer manifest file
remove_action('wp_head', 'feed_links_extra', 3); //Remove the links to the extra feeds such as category feeds
remove_action('wp_head', 'index_rel_link'); //Remove index link (deprecated?)
remove_action('wp_head', 'start_post_rel_link', 10, 0); //Remove start link
remove_action('wp_head', 'parent_post_rel_link', 10, 0); //Remove previous link
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); //Remove relational links for the posts adjacent to the current post
//Add new image sizes (Given human-readible names in another function below)
//"max_size" custom image size is defined in /libs/Optimization.php
add_image_size('square', 512, 512, 1);
add_image_size('open_graph_large', 1200, 630, 1);
add_image_size('open_graph_small', 600, 315, 1);
add_image_size('twitter_large', 280, 150, 1);
add_image_size('twitter_small', 200, 200, 1);
}
//Give custom Nebula image sizes human readable names
public function image_size_human_names($sizes){
return array_merge($sizes, array(
'square' => 'Square',
'open_graph_large' => 'Open Graph (Large)',
'open_graph_small' => 'Open Graph (Small)',
'twitter_large' => 'Twitter (Large)',
'twitter_small' => 'Twitter (Small)',
));
}
//Add custom meta icon (favicon) sizes when the site_icon is used via the Customizer
public function site_icon_sizes($core_sizes){
$nebula_sizes = array(16, 32, 70, 150, 180, 192, 310);
$all_sizes = array_unique(array_merge($core_sizes, $nebula_sizes));
return $all_sizes;
}
//Register REST API routes/endpoints
public function rest_api_routes(){
register_rest_route('nebula/v2', '/autocomplete_search/', array('methods' => 'GET', 'callback' => array($this, 'rest_autocomplete_search'), 'permission_callback' => '__return_true')); //.../wp-json/nebula/v2/autocomplete_search?term=whatever&types=post|page
}
//Add the Posts RSS Feed back in
public function add_back_post_feed(){
echo '<link rel="alternate" type="application/rss+xml" title="RSS 2.0 Feed" href="' . get_bloginfo('rss2_url') . '" />';
}
//Set server timezone to match Wordpress
public function set_default_timezone(){
if ( $this->get_option('force_wp_timezone') ){
//@todo "Nebula" 0: Use null coalescing operator here if possible
$timezone_option = wp_timezone_string();
//If that returns an offset instead of a named timezone
if ( strpos($timezone_option, ':') !== false ){ //@todo "Nebula" 0: Update strpos() to str_contains() in PHP8
$date_timezone = wp_timezone();
if ( !empty($date_timezone->timezone) ){
$timezone_option = $date_timezone['timezone'];
}
}
//If we still do not have a usable option, default to Eastern Time
if ( empty($timezone_option) ){
$timezone_option = 'America/New_York';
}
date_default_timezone_set($timezone_option); //@todo "Nebula" 0: WordPress Health Check does not like this... but date() is wrong (uses UTC) without it...
}
}
//Add the Nebula note to the browser console (if enabled)
public function calling_card(){
if ( $this->is_desktop() && !is_customize_preview() ){
echo "<script>console.log('%c Created using Nebula " . esc_html($this->version('primary')) . "', 'padding: 2px 10px; background: #0098d7; color: #fff;');</script>";
}
}
//Get the location URI of the Service Worker JavaScript file.
//Override this in your child theme if changing the location or filename of the service worker.
public function sw_location($uri=true){
$override = apply_filters('pre_sw_location', null, $uri);
if ( isset($override) ){return $override;}
if ( !empty($uri) ){
return get_site_url() . '/sw.js';
}
return get_home_path() . 'sw.js';
}
//Update variables within the service worker JavaScript file for install caching
public function update_sw_js($version=false){
$this->timer('Update SW');
$override = apply_filters('pre_nebula_update_swjs', null);
if ( isset($override) ){return;}
if ( empty($version) ){
$version = apply_filters('nebula_sw_cache_version', $version);
}
WP_Filesystem();
global $wp_filesystem;
$sw_js = $wp_filesystem->get_contents($this->sw_location(false));
if ( !empty($sw_js) ){
$find = array(
"/(const THEME_NAME = ')(.+)(';)/m",
"/(const NEBULA_VERSION = ')(.+)(';)(.+$)?/m",
"/(const OFFLINE_URL = ')(.+)(';)/m",
"/(const OFFLINE_IMG = ')(.+)(';)/m",
"/(const META_ICON = ')(.+)(';)/m",
"/(const MANIFEST = ')(.+)(';)/m",
"/(const HOME_URL = ')(.+)(';)/m",
"/(const START_URL = ')(.+)(';)/m",
);
//$new_cache_name = "nebula-" . strtolower(get_option('stylesheet')) . "-" . random_int(100000, 999999); //PHP 7.4 use numeric separators here
$replace = array(
"$1" . strtolower(get_option('stylesheet')) . "$3",
"$1" . 'v' . $version . "$3 //" . date('l, F j, Y g:i:s A'),
"$1" . home_url('/') . "offline/$3",
"$1" . get_theme_file_uri('/assets/img') . "/offline.svg$3",
"$1" . get_theme_file_uri('/assets/img/meta') . "/android-chrome-512x512.png$3",
"$1" . $this->manifest_json_location() . "$3",
"$1" . home_url('/') . "$3",
"$1" . home_url('/') . "?utm_source=pwa$3", //If getting "start_url does not respond" when offline in Lighthouse, make sure you are not disabling the cache in DevTools Network tab!
);
$sw_js = preg_replace($find, $replace, $sw_js);
$update_sw_js = $wp_filesystem->put_contents($this->sw_location(false), $sw_js);
do_action('nebula_wrote_sw_js');
do_action('qm/info', 'Updated sw.js File');
}
$this->timer('Update SW', 'end');
return false;
}
//Manifest JSON file location
public function manifest_json_location($uri=true){
$override = apply_filters('pre_manifest_json_location', null, $uri);
if ( isset($override) ){return $override;}
if ( !empty($uri) ){
return get_theme_file_uri('/inc/manifest.json');
}
return get_theme_file_path('/inc/manifest.json');
}
//Create/Write a manifest JSON file
public function manifest_json(){
$timer_name = $this->timer('Write Manifest JSON', 'start', 'Manifest');
$override = apply_filters('pre_nebula_manifest_json', null);
if ( isset($override) ){return;}
$manifest_json = '{
"name": "' . get_bloginfo('name') . ': ' . get_bloginfo('description') . '",
"short_name": "' . get_bloginfo('name') . '",
"description": "' . get_bloginfo('description') . '",
"theme_color": "' . get_theme_mod('nebula_primary_color', $this->get_color('$primary_color')) . '",
"background_color": "' . get_theme_mod('nebula_background_color', $this->get_color('$background_color')) . '",
"gcm_sender_id": "' . $this->get_option('gcm_sender_id') . '",
"scope": "/",
"start_url": "' . home_url('/') . '?utm_source=pwa",
"display": "standalone",
"orientation": "portrait",';
$shortcuts = apply_filters('nebula_manifest_shortcuts', array()); //Allow the child theme (or plugins) to add shortcuts to the PWA
if ( !empty($shortcuts) ){
$manifest_json .= '"shortcuts": ' . wp_json_encode($shortcuts, JSON_PRETTY_PRINT) . ',';
}
$manifest_json .= '"icons": [';
if ( has_site_icon() ){
$manifest_json .= '{
"src": "' . get_site_icon_url(16, get_theme_file_uri('/assets/img/meta') . '/favicon-16x16.png') . '",
"sizes": "16x16",
"type": "image/png"
}, {
"src": "' . get_site_icon_url(32, get_theme_file_uri('/assets/img/meta') . '/favicon-32x32.png') . '",
"sizes": "32x32",
"type": "image/png"
}, {
"src": "' . get_site_icon_url(192, get_theme_file_uri('/assets/img/meta') . '/android-chrome-192x192.png') . '",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
}, {
"src": "' . get_site_icon_url(512, get_theme_file_uri('/assets/img/meta') . '/android-chrome-512x512.png') . '",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}';
} else {
//Loop through all meta images
$files = glob(get_theme_file_path('/assets/img/meta') . '/*.png');
foreach ( $files as $file ){
$filename = $this->url_components('filename', $file);
$dimensions = getimagesize($file); //Considering adding an @ to ignore notices when getimagesize fails
if ( !empty($dimensions) ){
$manifest_json .= '{
"src": "' . get_theme_file_uri('/assets/img/meta') . '/' . $filename . '",
"sizes": "' . $dimensions[0] . 'x' . $dimensions[1] . '",
"type": "image/png",
"purpose": "any maskable"
}, ';
}
}
}
$manifest_json = rtrim($manifest_json, ', ') . ']}';
WP_Filesystem();
global $wp_filesystem;
$wp_filesystem->put_contents($this->manifest_json_location(false), $manifest_json);
do_action('qm/info', 'Updated manifest.json File');
$this->timer($timer_name, 'end');
}
//Redirect to favicon to force-clear the cached version when ?favicon is added to the URL.
public function favicon_cache(){
if ( array_key_exists('favicon', $this->super->get) ){
header('Location: ' . get_theme_file_uri('/assets/img/meta') . '/favicon.ico');
exit;
}
}
//Convenience function to return only the URL for specific thumbnail sizes of an ID.
public function get_thumbnail_src($img=null, $size='full', $type='post'){
if ( empty($img) ){
return false;
}
//If HTML is passed, immediately parse it with HTML
if ( strpos($img, '<img') !== false ){ //@todo "Nebula" 0: Update strpos() to str_contains() in PHP8
return ( preg_match('~\bsrc="([^"]++)"~', $img, $matches) )? $matches[1] : ''; //Pull the img src from the HTML tag itself
}
$id = intval($img); //Can now use the ID
//If and ID was not passed, immediately return it (in case it is already an image URL)
if ( $id === 0 || ($id === 1 && $img != 1) ){
return $img;
}
$size = apply_filters('nebula_thumbnail_src_size', $size, $id);
//If an attachment ID (or thumbnail ID) was passed
if ( get_post_type($id) === 'attachment' || $type !== 'post' ){
$image = wp_get_attachment_image_src(get_post_thumbnail_id($id), $size);
if ( !empty($image[0]) ){
return $image[0];
}
}
//Otherwise get the HTML from the post ID (or if the attachment src did not work above)
$img_tag = get_the_post_thumbnail($id, $size);
if ( get_post_type($id) === 'attachment' ){
$img_tag = wp_get_attachment_image($id, $size);
}
return ( preg_match('~\bsrc="([^"]++)"~', $img_tag, $matches) )? $matches[1] : ''; //Pull the img src from the HTML tag itself
}
//Sets the current post/page template to a variable.
function define_current_template($template){
$this->current_theme_template = str_replace(ABSPATH . 'wp-content', '', $template);
return $template;
}
//Show different meta data information about the post. Typically used inside the loop.
//Example: post_meta('by');
public function post_meta($meta, $options=array()){
$override = apply_filters('pre_post_meta', null, $meta, $options);
if ( isset($override) ){return;}
if ( $meta === 'date' || $meta === 'time' || $meta === 'on' || $meta === 'day' || $meta === 'when' ){
echo $this->post_date($options);
} elseif ( $meta === 'author' || $meta === 'by' ){
echo $this->post_author($options);
} elseif ( $meta === 'type' || $meta === 'cpt' || $meta === 'post_type' ){
echo $this->post_type($options);
} elseif ( $meta === 'categories' || $meta === 'category' || $meta === 'cat' || $meta === 'cats' || $meta === 'in' ){
echo $this->post_categories($options);
} elseif ( $meta === 'tags' || $meta === 'tag' ){
echo $this->post_tags($options);
} elseif ( $meta === 'dimensions' || $meta === 'size' ){
echo $this->post_dimensions($options);
} elseif ( $meta === 'exif' || $meta === 'camera' ){
echo $this->post_exif($options);
} elseif ( $meta === 'comments' || $meta === 'comment' ){
echo $this->post_comments($options);
} elseif ( $meta === 'social' || $meta === 'sharing' || $meta === 'share' ){
$this->social(array('facebook', 'twitter', 'linkedin', 'pinterest'), 0);
}
}
//Date post meta
public function post_date($options=array()){
$defaults = apply_filters('nebula_post_date_defaults', array(
'label' => 'icon', //"icon" or "text"
'type' => 'published', //"published", or "modified"
'relative' => get_theme_mod('post_date_format'),
'linked' => true,
'day' => true,
'format' => 'F j, Y',
));
$data = array_merge($defaults, $options);
if ( $data['relative'] === 'disabled' ){
return false;
}
//Apply the requested label
$label = '';
if ( $data['label'] == 'icon' ){
$label = '<i class="nebula-post-date-label fa-regular fa-fw fa-calendar"></i> ';
} elseif ( $data['label'] == 'text' ){
$label = '<span class="nebula-post-date-label">' . esc_html(ucwords($data['type'])) . ' </span>';
}
//Use the publish or modified date per options
$the_date = get_the_date('U');
$modified_date_html = '';
if ( $data['type'] === 'modified' ){
$the_date = get_the_modified_date('U');
}
$relative_date = human_time_diff($the_date) . ' ago';
if ( $data['relative'] ){
return '<time class="posted-on meta-item post-date relative-date" title="' . date('F j, Y', $the_date) . '">' . $label . $relative_date . $modified_date_html . '</time>';
}
$day = ( $data['day'] )? date('d', $the_date) . '/' : ''; //If the day should be shown (otherwise, just month and year).
if ( $data['linked'] && !isset($options['format']) ){
return '<span class="posted-on meta-item post-date">' . $label . '<time class="entry-date" datetime="' . date('c', $the_date) . '" itemprop="datePublished" content="' . date('c', $the_date) . '"><a href="' . home_url('/') . date('Y/m', $the_date) . '/">' . date('F', $the_date) . '</a> <a href="' . home_url('/') . date('Y/m', $the_date) . '/' . $day . '">' . date('j', $the_date) . '</a>, <a href="' . home_url('/') . date('Y', $the_date) . '/">' . date('Y', $the_date) . '</a></time>' . $modified_date_html . '</span>';
} else {
return '<span class="posted-on meta-item post-date">' . $label . '<time class="entry-date" datetime="' . date('c', $the_date) . '" itemprop="datePublished" content="' . date('c', $the_date) . '">' . date($data['format'], $the_date) . '</time>' . $modified_date_html . '</span>';
}
}
//Author post meta
public function post_author($options=array()){
$defaults = apply_filters('nebula_post_author_defaults', array(
'label' => 'icon', //"icon" or "text"
'linked' => true, //Link to author page
'force' => false, //Override author_bios Nebula option
));
$data = array_merge($defaults, $options);
//Include support for multi-authors: is_multi_author
if ( ($this->get_option('author_bios') || $data['force']) && get_theme_mod('post_author', true) ){
$label = '';
if ( $data['label'] === 'icon' ){
$label = '<i class="nebula-post-author-label fa-solid fa-fw fa-user"></i> ';
} elseif ( $data['label'] === 'text' ){
$label = '<span class="nebula-post-author-label">Author </span>';
}
//Get the author metadata
$author_id = get_the_author_meta('ID');
if ( empty($author_id) ){ //Author ID can be empty outside of the loop
global $post;
$author_id = $post->post_author;
$author_name = get_the_author_meta('display_name', $author_id);
} else {
$author_name = get_the_author();
}
if ( $data['linked'] && !$data['force'] ){
return '<span class="posted-by" itemprop="author" itemscope itemtype="https://schema.org/Person">' . $label . '<span class="meta-item entry-author"><a href="' . get_author_posts_url($author_id) . '" itemprop="name">' . $author_name . '</a></span></span>';
} else {
return '<span class="posted-by" itemprop="author" itemscope itemtype="https://schema.org/Person">' . $label . '<span class="meta-item entry-author" itemprop="name">' . esc_html($author_name) . '</span></span>';
}
}
}
//Post type meta
public function post_type($options=array()){
$defaults = apply_filters('nebula_post_type_defaults', array(
'icon' => true, //True for generic defaults, false to disable icon, or string of class name(s) for icon.
'linked' => false //True links output to the post type archive page
));
$data = array_merge($defaults, $options);
$post_icon_img = false;
if ( get_theme_mod('search_result_post_types', true) ){
global $wp_post_types;
$post_type = get_post_type();
$post_type_labels = get_post_type_object( $post_type )->labels;
if ( $data['icon'] ){
$post_icon = $wp_post_types[$post_type]->menu_icon;
$post_icon_img = '<i class="fa-solid fa-thumbtack"></i>';
if ( !empty($post_icon) ){
$post_icon_img = '<img src="' . $post_icon . '" style="width: 16px; height: 16px;" loading="lazy" />';
if ( strpos('dashicons-', $post_icon) >= 0 ){ //@todo "Nebula" 0: Update strpos() to str_contains() in PHP8
$post_icon_img = '<i class="dashicons-before ' . $post_icon . '"></i>';
}
}
if ( gettype($data['icon']) === 'string' && $data['icon'] !== '' ){
$post_icon_img = '<i class="' . esc_html($data['icon']) . '"></i>';
}elseif ( $post_type === 'post' ){
$post_icon_img = '<i class="fa-solid fa-fw fa-thumbtack"></i>';
} elseif ( $post_type === 'page' ){
$post_icon_img = '<i class="fa-solid fa-fw fa-file-alt"></i>';
}
}
if ( $data['linked'] ){
return '<span class="meta-item post-type"><a href="' . esc_url(get_post_type_archive_link($post_type)) . '" title="See all ' . $post_type_labels->name . '">' . $post_icon_img . esc_html($post_type_labels->singular_name) . '</a></span>';
}
return '<span class="meta-item post-type">' . $post_icon_img . esc_html($post_type_labels->singular_name) . '</span>';
}
}
//Categories post meta
public function post_cats($options=array()){return $this->post_categories($options);}
public function post_categories($options=array()){
$defaults = apply_filters('nebula_post_categories_defaults', array(
'id' => get_the_ID(),
'label' => 'icon', //"icon" or "text"
'linked' => true, //Link to category archive
'show_uncategorized' => true, //Show "Uncategorized" category
'force' => false,
'string' => false, //Return a string with no markup
));
$data = array_merge($defaults, $options);
if ( get_theme_mod('post_categories', true) || $data['force'] ){
$label = '';
if ( $data['label'] === 'icon' ){
$label = '<i class="nebula-post-categories-label fa-solid fa-fw fa-bookmark"></i> ';
} elseif ( $data['label'] === 'text' ){
$label = '<span class="nebula-post-categories-label">' . __('Category', 'nebula') . '</span>';
}
if ( is_object_in_taxonomy(get_post_type(), 'category') ){
$category_list = get_the_category_list(', ', '', $data['id']);
if ( strip_tags($category_list) === 'Uncategorized' && !$data['show_uncategorized'] ){
return false;
}
if ( !$data['linked'] ){
$category_list = strip_tags($category_list);
}
if ( $data['string'] ){
return strip_tags($category_list);
}
return '<span class="posted-in meta-item post-categories">' . $label . $category_list . '</span>';
}
}
}
//Tags post meta
public function post_tags($options=array()){
$defaults = apply_filters('nebula_post_tags_defaults', array(
'id' => get_the_ID(),
'label' => 'icon', //"icon" or "text"
'linked' => true, //Link to tag archive
'force' => false,
'string' => false, //Return a string with no markup
));
$data = array_merge($defaults, $options);
if ( get_theme_mod('post_tags', true) || $data['force'] ){
$tag_list = get_the_tag_list('', ', ', '', $data['id']);
if ( $tag_list ){
$label = '';
if ( $data['label'] === 'icon' ){
$the_tags = get_the_tags();
$tag_plural = ( !empty($the_tags) && is_array($the_tags) && count($the_tags) > 1 )? __('tags', 'nebula') : __('tag', 'nebula'); //One time get_the_tags() was not an array and caused a PHP error, so this conditional is for extra precaution
$label = '<i class="nebula-post-tags-label fa-solid fa-fw fa-' . $tag_plural . '"></i> ';
} elseif ( $data['label'] === 'text' ){
$label = '<span class="nebula-post-tags-label">' . ucwords($tag_plural) . ' </span>';
}
if ( !$data['linked'] ){
$tag_list = strip_tags($tag_list);
}
if ( $data['string'] ){
return strip_tags($tag_list);
}
return '<span class="posted-in meta-item post-tags">' . $label . $tag_list . '</span>';
}
}
}
//Image dimensions post meta
public function post_dimensions($options=array()){
if ( wp_attachment_is_image() ){
$defaults = array(
'icon' => true, //Show icon
'linked' => true, //Link to attachment
);
$data = array_merge($defaults, $options);
$the_icon = '';
if ( $data['icon'] ){
$the_icon = '<i class="fa-solid fa-fw fa-expand"></i> ';
}
$metadata = wp_get_attachment_metadata();
if ( $data['linked'] ){
echo '<span class="meta-item meta-dimensions">' . $the_icon . '<a href="' . wp_get_attachment_url() . '" >' . $metadata['width'] . ' × ' . $metadata['height'] . '</a></span>';
} else {
echo '<span class="meta-item meta-dimensions">' . $the_icon . $metadata['width'] . ' × ' . $metadata['height'] . '</span>';
}
}
}
//Image EXIF post meta
public function post_exif($icon=true){
$the_icon = '';
if ( $icon ){
$the_icon = '<i class="fa-solid fa-fw fa-camera-retro"></i> ';
}
$imgmeta = wp_get_attachment_metadata();
if ( $imgmeta ){ //Check for Bad Data
if ( $imgmeta['image_meta']['focal_length'] === 0 || $imgmeta['image_meta']['aperture'] === 0 || $imgmeta['image_meta']['shutter_speed'] === 0 || $imgmeta['image_meta']['iso'] === 0 ){
$output = __('No valid EXIF data found', 'nebula');
} else { //Convert the shutter speed retrieve from database to fraction
if ( $imgmeta['image_meta']['shutter_speed'] > 0 && (1/$imgmeta['image_meta']['shutter_speed']) > 1 ){
if ( (number_format((1/$imgmeta['image_meta']['shutter_speed']), 1)) == 1.3 || number_format((1/$imgmeta['image_meta']['shutter_speed']), 1) == 1.5 || number_format((1/$imgmeta['image_meta']['shutter_speed']), 1) == 1.6 || number_format((1/$imgmeta['image_meta']['shutter_speed']), 1) == 2.5 ){
$pshutter = '1/' . number_format((1/$imgmeta['image_meta']['shutter_speed']), 1, '.', '') . ' ' . __('second', 'nebula');
} else {
$pshutter = '1/' . number_format((1/$imgmeta['image_meta']['shutter_speed']), 0, '.', '') . ' ' . __('second', 'nebula');
}
} else {
$pshutter = $imgmeta['image_meta']['shutter_speed'] . ' ' . __('seconds', 'nebula');
}
$output = '<time datetime="' . date('c', $imgmeta['image_meta']['created_timestamp']) . '"><span class="month">' . date('F', $imgmeta['image_meta']['created_timestamp']) . '</span> <span class="day">' . date('j', $imgmeta['image_meta']['created_timestamp']) . '</span><span class="suffix">' . date('S', $imgmeta['image_meta']['created_timestamp']) . '</span> <span class="year">' . date('Y', $imgmeta['image_meta']['created_timestamp']) . '</span></time>, ';
$output .= $imgmeta['image_meta']['camera'] . ', ';
$output .= $imgmeta['image_meta']['focal_length'] . 'mm, ';
$output .= '<span style="font-style: italic; font-family: "Trebuchet MS", "Candara", "Georgia", serif; text-transform: lowercase;">f</span>/' . $imgmeta['image_meta']['aperture'] . ', ';
$output .= $pshutter . ', ';
$output .= $imgmeta['image_meta']['iso'] . ' ISO';
}
} else {
$output = __('No EXIF data found', 'nebula');
}
return '<span class="meta-item meta-exif">' . $the_icon . $output . '</span>';
}
//Use this instead of the_excerpt(); and get_the_excerpt(); to have better control over the excerpt.
//Inside the loop (or outside the loop for current post/page): nebula()->excerpt(array('words' => 20, 'ellipsis' => true));
//Outside the loop: nebula()->excerpt(array('id' => 572, 'words' => 20, 'ellipsis' => true));
//Custom text: nebula()->excerpt(array('text' => 'Lorem ipsum <strong>dolor</strong> sit amet.', 'more' => 'Continue »', 'words' => 3, 'ellipsis' => true, 'strip_tags' => true));
public function excerpt($options=array()){
$override = apply_filters('pre_nebula_excerpt', null, $options);
if ( isset($override) ){return $override;}
$defaults = apply_filters('nebula_excerpt_defaults', array(
'id' => false,
'text' => false,
'paragraphs' => false, //Allow paragraph tags in the excerpt //@todo "Nebula" 0: currently not working
'characters' => false,
'words' => get_theme_mod('nebula_excerpt_length', 55),
'length' => false, //Used for dynamic length, otherwise an alias of "words"
'min' => 0, //Minimum length of dynamic sentence
'ellipsis' => false,
'url' => false,
'more' => get_theme_mod('nebula_excerpt_more_text', __('Read More', 'nebula') . ' »'),
'wp_more' => true, //Listen for the WP more tag
'btn' => false, //Alias of "button"
'button' => false,
'strip_shortcodes' => true,
'strip_tags' => true,
'wrap_links' => false,
'shorten_urls' => false, //Currently only works with wrap_links
));
$data = array_merge($defaults, $options);
//Establish text
if ( empty($data['text']) ){
if ( !empty($data['id']) ){
if ( is_object($data['id']) && get_class($data['id']) == 'WP_Post' ){ //If we already have a WP_Post class object
$the_post = $data['id'];
} elseif ( intval($data['id']) ){ //If an ID is passed
$the_post = get_post(intval($data['id']));
}
} else {
$the_post = get_post(get_the_ID());
}
if ( empty($the_post) ){
return false;
}
if ( !empty($the_post->post_excerpt) ){
$data['text'] = $the_post->post_excerpt;
} else {
$data['text'] = $the_post->post_content;
if ( $data['wp_more'] ){
$wp_more_split = get_extended($the_post->post_content); //Split the content on the WordPress <!--more--> tag
$data['text'] = $wp_more_split['main'];
if ( preg_match('/<!--more(.*?)?-->/', $the_post->post_content, $matches) ){ //Get the custom <!--more Keep Reading--> text. RegEx from: https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/post-template.php#L288
if ( !empty($matches[1]) ){
$data['more'] = strip_tags(wp_kses_no_null(trim($matches[1])));
}
}
}
}
}
//Strip Newlines
$data['text'] = str_replace(array("\r\n", "\r", "\n"), " ", $data['text']); //Replace newline characters (keep double quotes)
$data['text'] = preg_replace('/\s+/', ' ', $data['text']); //Replace multiple spaces with single space
//Strip Shortcodes
if ( $data['strip_shortcodes'] ){
$data['text'] = strip_shortcodes($data['text']);
} else {
$data['text'] = preg_replace('~(?:\[/?)[^/\]]+/?\]~s', ' ', $data['text']);
}
//Strip Tags
if ( $data['strip_tags'] ){
$allowable_tags = ( !empty($data['paragraphs']) )? 'p' : '';
$data['text'] = strip_tags($data['text'], $allowable_tags);
}
//Apply string limiters (words or characters)
if ( !empty($data['characters']) && intval($data['characters']) ){ //Characters
$limited = $this->string_limit_chars($data['text'], intval($data['characters'])); //Returns array: $limited['text'] is the string, $limited['is_limited'] is boolean if it was limited or not.
$data['text'] = trim($limited['text']);
} elseif ( (!empty($data['words']) && intval($data['words'])) || (!empty($data['length']) && intval($data['length'])) ){ //Words (or Length)
$word_limit = ( !empty($data['length']) && intval($data['length']) )? intval($data['length']) : intval($data['words']);
$limited = $this->string_limit_words($data['text'], $word_limit); //Returns array: $limited['text'] is the string, $limited['is_limited'] is boolean if it was limited or not.
$data['text'] = trim($limited['text']);
}
//Apply dynamic sentence length limiter
if ( $data['length'] === 'dynamic' ){
$last_punctuation = -1;
foreach ( array('.', '?', '!') as $punctuation ){
if ( strrpos($data['text'] . ' ', $punctuation . ' ') ){
$this_punctuation = strrpos($data['text'] . ' ', $punctuation . ' ')+1; //Find the last punctuation (add a space to the end of the string in case it already ends at the punctuation). Add 1 to capture the punctuation, too.
if ( $this_punctuation > $last_punctuation ){
$last_punctuation = $this_punctuation;
}
}
}
if ( $last_punctuation >= $data['min'] ){
$data['text'] = substr($data['text'], 0, $last_punctuation); //Remove everything after the last punctuation in the string.
}
}
//Check here for links to wrap
if ( $data['wrap_links'] ){
$data['text'] = preg_replace('/(\(?(?:(http|https|ftp):\/\/)?(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]]*))?([\#][^\s\n]*)?\)?)(?![^<]*<\/)/i', '<a class="nebula-excerpt-url" href="$1">$1</a>', $data['text']); //Capture any URL not within < and </ using a negative lookahead (so it plays nice in case strip_tags is false)
}
//Shorten visible URL text
if ( $data['shorten_urls'] ){
$data['text'] = preg_replace_callback('/(<a.+>)(.+)(<\/a>)/', function($matches){
$output = $matches[1];
if ( strlen($matches[2]) > 20 ){
$short_url = str_replace(array('http://', 'https://'), '', $matches[2]);
$url_directories = explode('/', $short_url);
$short_url = $url_directories[0];
if ( count($url_directories) > 1 ){
$short_url .= '/...';
}
$output .= $short_url;
} else {
$output .= $matches[2];
}
$output .= $matches[3];
return $output;
}, $data['text']);
}
//Ellipsis
if ( $data['ellipsis'] && !empty($limited['is_limited']) ){
$data['text'] .= '…';
}
//Link
if ( !empty($data['more']) ){
if ( empty($data['url']) ){ //If has "more" text, but no link URL
$data['url'] = ( !empty($data['id']) )? get_permalink($data['id']) : get_permalink(get_the_id()); //Use the ID if available, or use the current ID.
}
//Button
$btn_class = '';
if ( $data['button'] || $data['btn'] ){
$button = ( $data['button'] )? $data['button'] : $data['btn'];
$btn_class = ( is_bool($button) )? 'btn btn-brand' : 'btn ' . $data['button'];
$data['text'] .= '<br /><br />';
}
$data['text'] .= ' <a class="nebula_excerpt ' . $btn_class . '" href="' . $data['url'] . '">' . $data['more'] . '</a>';
}
return $data['text'];
}
//Get the word count of a post
public function word_count($options=array()){
$override = apply_filters('pre_nebula_word_count', null, $options);
if ( isset($override) ){return $override;}
$defaults = array(
'id' => get_the_id(),
'content' => false,
'range' => false, //Show a range instead of exact count
);
$data = array_merge($defaults, $options);
$content = ( !empty($data['content']) )? $data['content'] : get_post_field('post_content', $data['id']);
$content = apply_filters('nebula_word_count', $content, $data['id']); //Allow additional content to be added to the word count (such as ACF fields)
$word_count = intval(round(str_word_count(strip_tags($content))));
if ( is_int($word_count) ){
if ( !$data['range'] ){
return $word_count;
}
$words_label = __('words', 'nebula');
if ( $word_count < 10 ){
$word_count_range = '<10 ' . $words_label;
} elseif ( $word_count < 500 ){
$word_count_range = '10 - 499 ' . $words_label;
} elseif ( $word_count < 1000 ){
$word_count_range = '500 - 999 ' . $words_label;
} elseif ( $word_count < 1500 ){
$word_count_range = '1,000 - 1,499 ' . $words_label;
} elseif ( $word_count < 2000 ){
$word_count_range = '1,500 - 1,999 ' . $words_label;
} else {
$word_count_range = '2,000+ ' . $words_label;
}
return $word_count_range;
}
return false;
}
//Determines the estimated time to read a post (in minutes).
//Note: Does not account for ACF fields unless hooked into 'nebula_word_count' above
public function estimated_reading_time($id=false){
//@todo "Nebula" 0: Use null coalescing operator here if possible
if ( empty($id) ){
$id = get_the_ID();
}
$wpm = 250; //Words per minute reading speed
$content = $this->word_count(array('id' => $id));
return intval(round($content/$wpm));
}
//Use WP Pagenavi if active, or manually paginate.
public function paginate($query=false, $args=array()){
if ( function_exists('wp_pagenavi') ){
wp_pagenavi();
} else {
if( !$query ){
global $wp_query;
$query = $wp_query;
}
$big = 999999999; //An unlikely integer //PHP 7.4 use numeric separators here
//Set some defaults if not passed by the $args value...
$args['base'] = ( !empty($args['base']) )? $args['base'] : str_replace($big, '%#%', esc_url(get_pagenum_link($big)));
$args['format'] = ( !empty($args['format']) )? $args['format'] : '?paged=%#%';
$args['current'] = ( !empty($args['current']) )? $args['current'] : max(1, get_query_var('paged'));
$args['total'] = ( !empty($args['total']) )? $args['total'] : $query->max_num_pages;
echo '<div class="wp-pagination">';
echo paginate_links($args);
echo '</div>';
}
}
//A consistent way to link to social network profiles
public function social_link($network){return $this->social_url($network);}
public function social_url($network){
switch ( strtolower($network) ){
case 'facebook':
case 'fb':
return esc_url($this->get_option('facebook_url'));
case 'twitter':
case 'x':
return $this->twitter_url(); //Use the provided function from Nebula Options
case 'linkedin':
return esc_url($this->get_option('linkedin_url'));
case 'instagram':
case 'ig':
return esc_url($this->get_option('instagram_url'));