-
Notifications
You must be signed in to change notification settings - Fork 34
/
functions.php
715 lines (626 loc) · 24.4 KB
/
functions.php
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
<?php // phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols
use P4\MasterTheme\Api;
use P4\MasterTheme\Loader;
use P4\MasterTheme\MediaArchive\Rest;
use P4\MasterTheme\Post;
use Timber\Timber;
use Timber\Menu as TimberMenu;
// This theme vendor dir
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
}
// Local env base vendor dir
if (file_exists(WP_CONTENT_DIR . '/vendor/autoload.php')) {
require_once WP_CONTENT_DIR . '/vendor/autoload.php';
}
// Prod env base vendor dir
if (file_exists(dirname(ABSPATH) . '/vendor/autoload.php')) {
require_once dirname(ABSPATH) . '/vendor/autoload.php';
}
/**
* A simpler way to add a filter that only returns a static value regardless of the input.
*
* @param string $filter_name The WordPress filter.
* @param mixed $value The value to be returned by the filter.
* @param int|null $priority The priority for the filter.
*
*/
function simple_value_filter(string $filter_name, $value, ?int $priority = null): void
{
add_filter(
$filter_name,
static function () use ($value) {
return $value;
},
$priority,
0
);
}
/**
* Generate a bunch of placeholders for use in an IN query.
* Unfortunately WordPress doesn't offer a way to do bind IN statement params, it would be a lot easier if we could pass
* the array to wpdb->prepare as a whole.
*
* @param array $items The items to generate placeholders for.
* @param int $start_index The start index to use for creating the placeholders.
* @param string $type The type of value.
*
* @return string The generated placeholders string.
*/
function generate_list_placeholders(array $items, int $start_index, string $type = 'd'): string
{
$placeholders = [];
foreach (range($start_index, count($items) + $start_index - 1) as $i) {
$placeholder = "%{$i}\${$type}";
// Quote it if it's a string.
if ('s' === $type) {
$placeholder = "'{$placeholder}'";
}
$placeholders[] = $placeholder;
}
return implode(',', $placeholders);
}
/**
* Wrapper function around cmb2_get_option.
*
* @param string $key Options array key.
* @param mixed $default The default value to use if the options is not set.
* @return mixed Option value.
*/
function planet4_get_option(string $key = '', $default = null)
{
$options = get_option('planet4_options');
return $options[ $key ] ?? $default;
}
// Timber loading
if (!class_exists(Timber::class)) {
add_action('admin_notices', function (): void {
echo '<div class="error"><p>Timber not activated. '
. 'Make sure you installed the composer package `timber/timber`.</p></div>';
});
add_filter(
'template_include',
fn() => get_stylesheet_directory() . '/static/no-timber.html'
);
return;
}
Timber::$cache = defined('WP_DEBUG') ? !WP_DEBUG : true;
$timber = new Timber();
add_action(
'rest_api_init',
function (): void {
Rest::register_endpoints();
Api\Gallery::register_endpoint();
Api\Search::register_endpoint();
Api\Settings::register_endpoint();
Api\Covers::register_endpoint();
Api\Articles::register_endpoint();
Api\SocialMedia::register_endpoint();
}
);
// Ensure no actions trigger a purge everything.
simple_value_filter('cloudflare_purge_everything_actions', []);
// Remove the menu item to the Cloudflare page.
add_action(
'admin_menu',
function (): void {
remove_submenu_page('options-general.php', 'cloudflare');
}
);
// remove_submenu_page does not prevent accessing the page. Add a higher prio action that dies instead.
add_action(
'settings_page_cloudflare',
function (): void {
die('This page is blocked to prevent excessive cache purging.');
},
1
);
/**
* Hide core updates notification in the dashboard, to avoid confusion while an upgrade is already in progress.
*/
function hide_wp_update_nag(): void
{
remove_action('admin_notices', 'update_nag', 3);
remove_filter('update_footer', 'core_update_footer');
}
add_action('admin_menu', 'hide_wp_update_nag');
require_once 'load-class-aliases.php';
Loader::get_instance();
// WP core's escaping logic doesn't take the case into account where a gradient is followed by a URL.
add_filter(
'safecss_filter_attr_allow_css',
function (bool $allow_css, $css_test_string) {
// Short circuit in case the CSS is already allowed.
// This filter only runs to catch the case where it's not allowed but should be.
if ($allow_css) {
return true;
}
$without_property = preg_replace('/.*:/', '', $css_test_string);
// Same regex as in WordPress core, except it matches anywhere in the string.
// See https://github.com/WordPress/WordPress/blob/a5293aa581802197b0dd7c42813ba137708ad0e1/wp-includes/kses.php#L2438.
$gradient_regex = '/(repeating-)?(linear|radial|conic)-gradient\(([^()]|rgb[a]?\([^()]*\))*\)/';
// Check if a gradient is still present.
// The only case where $css_test_string can still have this present is if it
// was missed by the faulty WP regex.
if (! preg_match($gradient_regex, $css_test_string)) {
return $allow_css;
}
$without_gradient = preg_replace($gradient_regex, '', trim($without_property));
return trim($without_gradient, ', ') === '';
},
10,
2
);
add_action(
'wpml_after_update_attachment_texts',
function ($original_attachment_id, $translation): void {
$original_sm_cloud = get_post_meta($original_attachment_id, 'sm_cloud', true);
update_post_meta($translation->element_id, 'sm_cloud', $original_sm_cloud);
},
1,
2
);
/**
* This is not a column in WordPress by default, but is added by the Post Type Switcher plugin.
* It's not needed for the plugin to work, and needlessly takes up space on pages where everything has the same post
* type.
*
* Showing the field is only somewhat useful when using quick edit to switch a single post from the admin listing page.
*/
add_filter(
'default_hidden_columns',
function ($hidden) {
$hidden[] = 'post_type';
return $hidden;
},
10,
1
);
/**
* TODO: Move to editor only area.
* Set the editor width per post type.
*/
add_filter(
'block_editor_settings_all',
function (array $editor_settings, WP_Block_Editor_Context $block_editor_context) {
if (isset($block_editor_context->post) && 'post' !== $block_editor_context->post->post_type) {
$editor_settings['__experimentalFeatures']['layout']['contentSize'] = '1320px';
}
return $editor_settings;
},
10,
2
);
/**
* I'll move this somewhere else in master theme.
*
*/
function register_more_blocks(): void
{
register_block_type(
'p4/reading-time',
[
'render_callback' => [ Post::class, 'reading_time_block' ],
'uses_context' => [ 'postId' ],
]
);
register_block_type(
'p4/post-author-name',
[
// phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter -- register_block_type callback
'render_callback' => function (array $attributes, $content, $block) {
$author_override = get_post_meta($block->context['postId'], 'p4_author_override', true);
$post_author_id = get_post_field('post_author', $block->context['postId']);
$is_override = ! empty($author_override);
$name = $is_override ? $author_override : get_the_author_meta('display_name', $post_author_id);
$link = $is_override ? '#' : get_author_posts_url($post_author_id);
$block_content = $author_override ? $name : "<a href='$link'>$name</a>";
return "<span class='article-list-item-author'>$block_content</span>";
},
'uses_context' => [ 'postId' ],
]
);
// Like the core block but with an appropriate sizes attribute.
// phpcs:disable Generic.Files.LineLength.MaxExceeded
register_block_type(
'p4/post-featured-image',
[
// phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter -- register_block_type callback
'render_callback' => function (array $attributes, $content, $block) {
$post_id = $block->context['postId'];
$post_link = get_permalink($post_id);
$featured_image = get_the_post_thumbnail(
$post_id,
null,
// For now hard coded sizes to the ones from Articles, as it's the single usage.
// This can be made a block attribute, or even construct a sizes attr with math based on context.
// For example, it could already access displayLayout from Query block to know how many columns are
// being rendered. If it then also knows the flex gap and container width, it should have all needed
// info to support a large amount of cases.
[ 'sizes' => '(min-width: 1600px) 389px, (min-width: 1200px) 335px, (min-width: 1000px) 281px, (min-width: 780px) 209px, (min-width: 580px) 516px, calc(100vw - 24px)' ]
);
return "<a href='$post_link'>$featured_image</a>";
},
'uses_context' => [ 'postId' ],
]
);
// Block displays related posts using the Query Loop block
register_block_type(
'p4/related-posts',
[
'attributes' => [
'query_attributes' => [
'type' => 'object',
'default' => [],
],
],
'render_callback' => 'render_related_posts_block',
]
);
register_block_type(
'p4/bottom-page-navigation-block',
[
'render_callback' => 'render_navigation_block',
]
);
}
add_action('init', 'register_more_blocks');
/**
* Custom block render function for Related posts
*
* @param array $attributes Array of dynamic attributes to render section.
*
* @return string HTML markup for front end.
*/
function render_related_posts_block(array $attributes): string
{
// Encode the query attributes to JSON for the block template
$query_json = wp_json_encode($attributes['query_attributes'], JSON_UNESCAPED_SLASHES);
// Dynamically render link to News & Stories page
$news_stories_url = '';
$news_stories_page = (int) get_option('page_for_posts');
if ($news_stories_page) {
$news_stories_url = get_permalink($news_stories_page);
}
$see_all_link_group = !empty($news_stories_url) ?
'<!-- wp:navigation-link {"label":"' . __('See all posts', 'planet4-blocks') . '","url":"' . $news_stories_url . '","className":"see-all-link"} /-->'
: '';
// Define the HTML output for the block
$output = '<!-- wp:query ' . $query_json . ' -->
<div class="wp-block-query posts-list p4-query-loop is-custom-layout-list">
<!-- wp:group {"layout":{"type":"flex","justifyContent":"space-between"}} -->
<div class="wp-block-group">
<!-- wp:heading -->
<h2 class="wp-block-heading">' . __('Related Posts', 'planet4-blocks') . '</h2>
<!-- /wp:heading -->
' . $see_all_link_group . '
</div>
<!-- /wp:group -->
<!-- wp:post-template -->
<!-- wp:columns -->
<div class="wp-block-columns">
<!-- wp:post-featured-image {"isLink":true} /-->
<!-- wp:group -->
<div class="wp-block-group">
<!-- wp:group {"layout":{"type":"flex"}} -->
<div class="wp-block-group">
<!-- wp:post-terms {"term":"category","separator":" | "} /-->
<!-- wp:post-terms {"term":"post_tag","separator":" "} /-->
</div>
<!-- /wp:group -->
<!-- wp:post-title {"isLink":true} /-->
<!-- wp:post-excerpt /-->
<!-- wp:group {"className":"posts-list-meta"} -->
<div class="wp-block-group posts-list-meta">
<!-- wp:p4/post-author-name /-->
<!-- wp:post-date /-->
</div>
<!-- /wp:group -->
</div>
<!-- /wp:group -->
</div>
<!-- /wp:columns -->
<!-- /wp:post-template -->
' . $see_all_link_group . '
</div>
<!-- /wp:query -->';
return do_blocks($output);
}
/**
* Custom block render function for Bottom page navigation
*
* @param array $attributes Array of dynamic attributes to render section.
*
* @return string HTML markup for front end.
*/
// phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
function render_navigation_block(array $attributes): string
{
global $post;
$menu = new TimberMenu('navigation-bar-menu');
$menu_items = $menu->get_items();
// Check if the current page is in the menu
$nav_menu_item = null;
foreach ($menu_items as $item) {
if ((int) $item->object_id === (int) $post->ID) {
$nav_menu_item = $item;
break;
}
}
// Check if the current page is a submenu item
$submenu_page = null;
foreach ($menu_items as $item) {
if (empty($item->children)) {
continue;
}
foreach ($item->children as $child) {
if ((int) $child->object_id === (int) $post->ID) {
$submenu_page = $child;
break 2;
}
}
}
// Omit the block if the page is not in the menu or submenu
if (!$nav_menu_item && !$submenu_page) {
return '';
}
// For parent pages, get the previous and next siblings in the menu order
$output = '';
$siblings = array_filter($menu_items, function ($item) use ($nav_menu_item) {
return $item->menu_item_parent === $nav_menu_item->menu_item_parent;
});
$siblings = array_values($siblings);
$current_index = array_search($nav_menu_item, $siblings);
if ($current_index !== false) {
$prev_item = $siblings[$current_index - 1] ?? null;
$next_item = $siblings[$current_index + 1] ?? null;
if ($prev_item) {
$output .= '<a href="' . esc_url($prev_item->url) . '" class="bottom-navigation-prev"><span class="bottom-navigation-link-text">' . esc_html($prev_item->title) . '</span></a>';
}
if ($next_item) {
$output .= '<a href="' . esc_url($next_item->url) . '" class="bottom-navigation-next"><span class="bottom-navigation-link-text">' . esc_html($next_item->title) . '</span></a>';
}
}
// For child pages, only show link to the parent
if ($submenu_page->menu_item_parent !== 0) {
$parent_item = array_filter($menu_items, function ($item) use ($submenu_page) {
return (int) $item->ID === (int) $submenu_page->menu_item_parent;
});
$parent_item = reset($parent_item);
if ($parent_item) {
$output = '<a href="' . esc_url($parent_item->url) . '" class="bottom-navigation-prev sub-nav-item"><span class="bottom-navigation-link-text">' . esc_html($parent_item->title) . '</span></a>';
}
}
return '<div class="container bottom-navigation">' . $output . '</div>';
}
add_filter(
'cloudflare_purge_by_url',
function ($urls, $post_id) {
// If new IA is not active return early since pagination is not being used.
if (empty(planet4_get_option('new_ia'))) {
return $urls;
}
$new_urls = [];
// Most of this logic is copied from the start of \CF\WordPress\Hooks::getPostRelatedLinks.
// I had to adapt it to our CS, it used snake case and old arrays.
// I only changed the part that creates the pagination URLs.
// And for now early return on other taxonomies as only tags need it.
$post_type = get_post_type($post_id);
// Purge taxonomies terms and feeds URLs.
$post_type_taxonomies = get_object_taxonomies($post_type);
foreach ($post_type_taxonomies as $taxonomy) {
// Only do post tags for now, but we'll need this loop when more pages have pagination.
if ('post_tag' !== $taxonomy) {
continue;
}
// Only if taxonomy is public.
$taxonomy_data = get_taxonomy($taxonomy);
if ($taxonomy_data instanceof WP_Taxonomy && false === $taxonomy_data->public) {
continue;
}
$terms = get_the_terms($post_id, $taxonomy);
if (empty($terms) || is_wp_error($terms)) {
continue;
}
foreach ($terms as $term) {
$term_link = get_term_link($term);
if (is_wp_error($term_link)) {
continue;
}
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => - 1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => [ $term->term_id ],
],
],
];
$query = new WP_Query($args);
$pages = $query->post_count / get_option('posts_per_page', 10);
if ($pages <= 1) {
continue;
}
$numbers = range(2, 1 + round($pages));
$new_urls = array_map(fn($i) => "{$term_link}page/{$i}/", $numbers);
}
}
return array_merge($urls, $new_urls);
},
10,
2
);
// Add filters to the News & Stories listing page.
// Right now only "category" and "post type" are available.
add_action(
'pre_get_posts',
function ($query): void {
if (!$query->is_main_query() || is_admin() || !is_home()) {
return;
}
// Category filter
$category_slug = isset($_GET['category']) ? $_GET['category'] : '';
$category = get_category_by_slug($category_slug);
$query->set('category__in', $category ? [$category->term_id] : []);
// Post type filter
$post_type_slug = isset($_GET['post-type']) ? $_GET['post-type'] : '';
$post_type = get_term_by('slug', $post_type_slug, 'p4-page-type');
$query->set('tax_query', !$post_type ? [] : [[
'taxonomy' => 'p4-page-type',
'field' => 'term_id',
'terms' => [$post_type->term_id],
]]);
}
);
// Calls attachment metadata update on importer job.
// This triggers the wp-stateless hook (if it exists),
// which sets the sm_cloud metadata for the uploaded file.
// Wp-stateless is then able to find the file on GCS on step 2,
// instead of looking for it in the local uploads folder.
add_action(
'add_attachment',
function ($post_id): void {
if (
! defined('WP_IMPORTING')
|| ! WP_IMPORTING
|| ! isset($_GET['step']) // phpcs:ignore WordPress.Security.NonceVerification
|| '1' !== $_GET['step'] // phpcs:ignore WordPress.Security.NonceVerification
|| ! class_exists('wpCloud\StatelessMedia\Bootstrap')
) {
return;
}
if (version_compare(\wpCloud\StatelessMedia\Bootstrap::$version, '3.0', '<')) {
return;
}
$post = get_post($post_id);
if (! $post || 'attachment' !== $post->post_type) {
return;
}
$cloud_meta = get_post_meta($post_id, 'sm_cloud', true);
if (! empty($cloud_meta)) {
return;
}
$metadata = wp_get_attachment_metadata($post_id);
wp_update_attachment_metadata($post_id, $metadata);
},
99
);
// WP Stateless plugin short-circuits the image_downsize() process
// with wpCloud\StatelessMedia\Bootstrap::image_downsize().
// Contrary to the native function, it will return attachment data
// even if the attachment is not an image.
// The attachment is then treated as an image by the function
// wp_get_attachment_link() generating the link, even for a PDF.
// We overrule wp-stateless response if file is not an image.
add_filter(
'image_downsize',
function ($downsize, $id) {
return wp_attachment_is_image($id) ? $downsize : false;
},
100,
2
);
// This action overrides the WordPress functionality for adding a notice message
// https://github.com/WordPress/wordpress-develop/blob/trunk/src/wp-admin/edit-form-blocks.php#L303-L305
// When it's a page for posts.
add_action(
'admin_enqueue_scripts',
function (): void {
global $post;
if (!$post || (int) get_option('page_for_posts') !== $post->ID) {
return;
}
// Adding this style, it works as a workaround for editors
// To disable the ability to edit the content of the listing page.
echo '<style>
.edit-post-header-toolbar,
.block-list-appender {
pointer-events: none;
opacity: 0;
}
.block-editor-block-list__layout {
display: none;
}
.components-notice__actions {
display: inline-flex !important;
margin-left: 5px;
}
</style>';
wp_add_inline_script(
'wp-notices',
sprintf(
'wp.data.dispatch( "core/notices" ).createNotice("warning", "%s" , { isDismissible: false, actions: [ { label: "%s", url: "/wp-admin/options-reading.php"} ] } )',
__('The content on this page is hidden because this page is being used as your \"All Posts\" listing page. You can disable this by un-setting the \"Posts page\"', 'planet4-master-theme'),
__('here', 'planet4-master-theme')
)
);
},
100
);
// The new `pagenum` query_var is used ONLY trough the default listing pages (index.php),
// when the Load more feature is enabled.
// Also added in replacement of the `page` query_var since that param is returning always zero.
add_filter(
'query_vars',
function ($vars) {
$vars[] = 'page_num';
return $vars;
}
);
// Action to filter P4 settings menu.
add_action(
'admin_head',
function (): void {
global $submenu;
if (!isset($submenu['planet4_settings_navigation'])) {
return;
}
uasort($submenu['planet4_settings_navigation'], fn ($a, $b) => $a[0] <=> $b[0]);
}
);
// This filter replaces the default Canonical URL with what is set in the Sidebar Options.
// If no URL is set for the Canonical link, the default WP url is used.
add_filter(
'get_canonical_url',
function ($canonical_url, $post) {
if (isset($post->p4_seo_canonical_url) && '' !== $post->p4_seo_canonical_url) {
$canonical_url = $post->p4_seo_canonical_url;
}
return $canonical_url;
},
10,
2
);
if (class_exists('\\Sentry\\Options')) {
add_filter('wp_sentry_options', function (\Sentry\Options $options) {
// Only sample 25% of the events
$options->setSampleRate(0.25);
return $options;
});
}
// Enable Hide Page title by default when Pattern Layout is used
add_action(
'transition_post_status',
function ($new_status, $old_status, $post): void {
// Check if the new status is 'publish' and the old status is not 'publish'
// And it is a Page
if ($new_status !== 'publish' || $old_status === 'publish' || $post->post_type === 'post') {
return;
}
// Parse the blocks in the post content
$blocks = parse_blocks($post->post_content);
// Check if the first block matches the regex
if (empty($blocks) || !preg_match('/^planet4-block-templates\/.*/', $blocks[0]['blockName'])) {
return;
}
// Update the 'hide_page_title' metadata
update_post_meta($post->ID, 'p4_hide_page_title_checkbox', 'on');
},
10,
3
);
// phpcs:enable Generic.Files.LineLength.MaxExceeded