Repository navigation
Expand file tree
/
Copy pathclass-widget.php
More file actions
2967 lines (2665 loc) · 112 KB
/
Copy pathclass-widget.php
File metadata and controls
2967 lines (2665 loc) · 112 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
/**
* Implementation of the widget class.
*
* @package categoryposts.
*
* @since 4.7
*/
namespace categoryPosts;
// Don't call the file directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Category Posts Widget Class
*
* Shows the single category posts with some configurable options
*/
class Widget extends \WP_Widget {
/**
* The settings for the instance currently being rendered/configured.
*
* Several helper methods (thumbnail rendering, excerpt filters, etc.) read
* this before it is necessarily populated by widget()/form(); declaring it
* (instead of relying on it being created as a dynamic property) means those
* reads get an empty array instead of an "undefined property" warning.
*
* @var array
*/
public $instance = array();
/**
* The page of the list shown, set by get_elements_HTML() for pagination.
*
* @var int
*/
public $current_page = 1;
/**
* The number of pages of the list, set by get_elements_HTML() for pagination.
*
* @var int
*/
public $total_pages = 0;
/**
* What the editor preview stands in for the page the list is on, resolved
* from the template or post being edited, see preview_context().
*
* @var array|null
*/
public $preview_context = null;
/**
* The slug of the template the editor preview is for, empty if none.
*
* @var string
*/
public $preview_template_slug = '';
/**
* The query variables of the page, for "load more" of a list which took
* over the query of the page, see inherited_query().
*
* @var array|null
*/
public $inherited_vars = null;
/**
* What the page is about, for "load more" of a list with "Query type:
* Matching" on a page without a current post, see page_context_vars().
*
* @var array|null
*/
public $page_context = null;
/**
* Widget constructor.
*/
public function __construct() {
$widget_ops = array(
'show_instance_in_rest' => true,
'classname' => 'cat-post-widget',
'description' => __( 'List single category posts', 'category-posts' ),
);
parent::__construct( WIDGET_BASE_ID, __( 'Category Posts', 'category-posts' ), $widget_ops );
}
/**
* Calculate the attachment size for showing the feature image
*
* The attachment size should for width and height greater than the widget image width and height settings.
*
* @param int $post_thumbnail_id The id of the featured image attachment.
* @return string The HTML for the thumb related to the post
*
* @since 4.9.22
*/
public function post_thumbnail_attachment_size( $post_thumbnail_id ) {
// $this->instance is only populated once the widget/shortcode/block render path has
// set it (e.g. via widget()); guard against it being unset to avoid PHP warnings.
$thumb_w = isset( $this->instance['thumb_w'] ) ? intval( $this->instance['thumb_w'] ) : 0;
$thumb_h = isset( $this->instance['thumb_h'] ) ? intval( $this->instance['thumb_h'] ) : 0;
// Get attachment image by size
$image_sizes = array('thumbnail', 'medium', 'large', 'full');
foreach ($image_sizes as $img_size) {
$attachment_img_size = wp_get_attachment_image_src($post_thumbnail_id, $img_size);
if ($attachment_img_size[1] >= $thumb_w && $attachment_img_size[2] >= $thumb_h && ! (0 === $thumb_w && 0 === $thumb_h) ||
'full' === $img_size) {
$html = wp_get_attachment_image(
$post_thumbnail_id,
$img_size,
false,
array
(
"data-cat-posts-width" => $thumb_w,
"data-cat-posts-height" => $thumb_h
)
);
break;
}
}
if ( ! $html ) {
return '';
}
return $html;
}
/**
* Calculate the HTML for showing the feature image of a post item.
*
* Used as a filter for the thumb wordpress API to add css based stretching and cropping
* when the image is not at the requested dimensions
*
* @param int $post_id the ID of the post of which the thumb is a featured image.
* @param int $post_thumbnail_id The id of the featured image attachment.
* @param string|array $size The requested size identified by name or (width, height) array.
* @param mixed $attr ignored in this context.
* @return string The HTML for the thumb related to the post
*
* @since 4.1
*/
public function post_thumbnail_html( $post_id, $post_thumbnail_id, $size, $attr ) {
$html = $this->post_thumbnail_attachment_size($post_thumbnail_id);
// normalize style
$html = preg_replace( '/style="([^"]*)"/i', '', $html );
// replace size.
$array = array();
preg_match( '/width="([^"]*)"/i', $html, $array );
$pattern = '/\s' . $array[1] . 'px/';
$html = preg_replace( $pattern, ' ' . $size[0] . 'px', $html );
// replace width.
$pattern = '/width="' . $array[1] . '"/';
if ( ! empty( $this->instance['thumb_w'] ) ) {
$html = preg_replace( $pattern, 'width="' . $size[0] . '"', $html );
} else {
$html = preg_replace( $pattern, '', $html );
}
// replace height
$array = array();
preg_match( '/height="([^"]*)"/i', $html, $array );
$pattern = '/height="' . $array[1] . '"/';
if ( ! empty( $this->instance['thumb_h'] ) ) {
$html = preg_replace( $pattern, 'height="' . $size[1] . '"', $html );
} else {
$html = preg_replace( $pattern, '', $html );
}
$show_post_format = isset( $this->instance['show_post_format'] ) && ( 'none' !== $this->instance['show_post_format'] );
$post_format_class = '';
if ( $show_post_format || ! empty( $this->instance['thumb_hover'] ) ) {
$format = get_post_format() ? : 'standard';
$post_format_class = 'cat-post-format cat-post-format-' . $format;
}
$html = '<span class="cat-post-crop ' . $post_format_class . '">' . $html . '</span>';
return $html;
}
/*
* wrapper to execute the the_post_thumbnail with filters.
*/
/**
* Calculate the HTML for showing the thumb of a post item.
*
* It is a wrapper to execute the the_post_thumbnail with filters
*
* @param string|array $size The requested size identified by name or (width, height) array.
*
* @return string The HTML for the thumb related to the post and empty string if it can not be calculated
*
* @since 4.1
*/
public function the_post_thumbnail( $size = 'post-thumbnail' ) {
// The image which is going to be rendered, which is not necessarily the
// featured image of the post: a post without one is shown with the default
// thumbnail when the settings name one. Resolved up here because a dimension
// left at 0 is filled in from this very image below.
$post_thumbnail_id = get_post_thumbnail_id( get_the_ID() );
if ( ! $post_thumbnail_id && ! empty( $this->instance['default_thunmbnail'] ) ) {
$post_thumbnail_id = $this->instance['default_thunmbnail'];
}
if ( empty( $size ) ) { // if junk value, make it a normal thumb.
// post_thumbnail_html() below always expects a [width, height] pixel
// pair to rewrite the width/height/sizes attributes with, not a named
// size string - passing through the string 'post-thumbnail' made it
// index into the string itself (e.g. $size[0] === 'p'), corrupting the
// generated markup (a "ppx" sizes attribute, wrong width/height).
$size = array( get_option( 'thumbnail_size_w', 150 ), get_option( 'thumbnail_size_h', 150 ) );
} elseif ( is_array( $size ) && ( 2 === count( $size ) ) ) { // good format at least.
// normalize to ints first.
list( $width, $height ) = array_map('intval', $size);
if ( ( 0 === $width ) && ( 0 === $height ) ) { // Both values zero then revert to ratio from the orig with large.
$size = array( get_option( 'large_size_w', 150 ), get_option( 'large_size_h', 150 ) );
} elseif ( ( 0 === $width ) || ( 0 === $height ) ) {
// Exactly one of the two is left to the image, so the other one has to
// come from the image itself. Ask the attachment for its dimensions
// instead of parsing them back out of get_the_post_thumbnail(): that
// only ever knows about a real featured image, so for a post shown with
// the default thumbnail it returned nothing at all, and the width and
// height read from that nothing made the ratio a division by zero.
$full = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );
$full_w = $full ? intval( $full[1] ) : 0;
$full_h = $full ? intval( $full[2] ) : 0;
if ( 0 === $width ) {
// The width follows the image, hand WordPress the full width for
// the rest of the markup.
$size[0] = $full_w;
} elseif ( $full_w && $full_h ) {
// The height follows the width through the ratio of the image.
$size[1] = intval( $width * $full_h / $full_w );
}
// An attachment which does not report its dimensions - an SVG without
// them in its meta data, or none at all because there is no image to
// show in the first place - leaves the 0 in place. post_thumbnail_html()
// then drops that attribute and getCSSRules() emits no rule for it,
// which is exactly what a 0 asks for: the browser keeps the ratio.
}
} else {
$size = array( get_option( 'thumbnail_size_w', 150 ), get_option( 'thumbnail_size_h', 150 ) ); // yet another form of junk.
}
do_action( 'begin_fetch_post_thumbnail_html', get_the_ID(), $post_thumbnail_id, $size );
$ret = $this->post_thumbnail_html( get_the_ID(), $post_thumbnail_id, $size, '' );
do_action( 'end_fetch_post_thumbnail_html', get_the_ID(), $post_thumbnail_id, $size );
return $ret;
}
/**
* Excerpt more link filter
*
* @param string $more The "more" text passed by the filter.
*
* @return string The link to the post with the "more" text configured in the widget.
*/
public function excerpt_more_filter( $more ) {
return ' <a class="cat-post-excerpt-more more-link" href="' . get_permalink() . '">' . esc_html( $this->instance['excerpt_more_text'] ) . '</a>';
}
/**
* Apply the_content filter for excerpt
* This should show sharing buttons which comes with other widgets in the widget output in the same way as on the main content
*
* @param string $text The HTML with other applied excerpt filters.
*
* @return string If option hide_social_buttons is unchecked applay the_content filter.
*
* @since 4.6
*/
public function apply_the_excerpt( $text ) {
$ret = apply_filters( 'the_content', $text );
return $ret;
}
/**
* The ID of the post to leave out when "Exclude current post" is active.
*
* On a singular page that is the current post. A "load more" request is a
* REST request without a singular context, there the ID the first page was
* rendered for is passed in. It comes from the client, so it is only taken
* when it belongs to a published post of a publicly viewable post type.
*
* @param array $instance Array which contains the various settings.
* @param int|string $singular_id The ID of the post the list was rendered in,
* empty or 0 if there is none.
*
* @return int The ID of the post to exclude, 0 if none.
*
* @since 5.1.3
*/
public function excluded_post_id( $instance, $singular_id = 0 ) {
if ( empty( $instance['exclude_current_post'] ) ) {
return 0;
}
if ( is_singular() ) {
return (int) get_the_ID();
}
$singular_id = (int) $singular_id;
if ( 0 < $singular_id
&& 'publish' === get_post_status( $singular_id )
&& is_post_type_viewable( get_post_type( $singular_id ) ) ) {
return $singular_id;
}
return 0;
}
/**
* Calculate the wp-query arguments matching the filter settings of the widget
*
* @param array $instance Array which contains the various settings.
* @param int|string $singular_id The ID of the post the list was rendered in, used
* to exclude it when loading more items. Optional.
* @return array The array that can be fed to wp_Query to get the relevant posts
*
* @since 4.6
*/
public function queryArgs( $instance, $singular_id = 0 ) {
$valid_sort_orders = array(
'date', 'title', 'comment_count', 'rand'
);
if ( isset( $instance['sort_by'] ) && in_array( $instance['sort_by'], $valid_sort_orders, true ) ) {
$sort_by = $instance['sort_by'];
} else {
$sort_by = 'date';
}
$sort_order = ( isset( $instance['asc_sort_order'] ) && $instance['asc_sort_order'] ) ? 'ASC' : 'DESC';
// start sticky posts
$ignore_sticky = isset( $instance['sticky'] ) && $instance['sticky'] ? false : true;
// Get array of post info.
$args = array(
'orderby' => $sort_by,
'order' => $sort_order,
'ignore_sticky_posts' => $ignore_sticky, // Make sure we do not get stickies out of order.
'no_found_rows' => true, // Do not count the total numbers of rows by default.
);
$non_default_valid_status = array(
'publish',
'future',
'publish,future',
'private',
'private,publish',
'private,publish,future',
);
if ( isset( $instance['status'] ) && in_array( $instance['status'], $non_default_valid_status, true ) ) {
$args['post_status'] = $instance['status'];
}
if ( isset( $instance['num'] ) ) {
$args['showposts'] = (int) $instance['num'];
}
if ( isset( $instance['offset'] ) && ( (int) $instance['offset'] > 1 ) ) {
$args['offset'] = (int) $instance['offset'] - 1;
}
if ( isset( $instance['cat'] ) ) {
if ( isset( $instance['no_cat_childs'] ) && $instance['no_cat_childs'] ) {
$args['category__in'] = (int) $instance['cat'];
} else {
$args['cat'] = (int) $instance['cat'];
}
}
$exclude_current_post = $this->excluded_post_id( $instance, $singular_id );
if ( $exclude_current_post ) {
$args['post__not_in'] = array( $exclude_current_post );
}
if ( isset( $instance['hideNoThumb'] ) && $instance['hideNoThumb'] ) {
$args = array_merge(
$args,
array(
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS',
),
),
)
);
}
switch ( isset( $instance['date_range'] ) ? $instance['date_range'] : 'off' ) {
case 'days_ago':
$ago = (int) $instance['days_ago'];
// If there is no valid integer value given, bail.
if ( 0 === $ago ) {
break;
}
$date = date( 'Y-m-d', strtotime( '-' . $ago . ' days' ) );
$args['date_query'] = array(
'after' => $date,
'inclusive' => true,
);
break;
case 'between_dates':
// Validation note - not doing any, assuming the query will
// fail gracefully enough for now as it is not clear what Should
// the validation be right now.
$start_date = $instance['start_date'];
$end_date = $instance['end_date'];
$args['date_query'] = array(
'after' => $start_date,
'before' => $end_date,
'inclusive' => true,
);
break;
}
return $args;
}
/**
* Calculate the HTML of the title based on the widget settings
*
* @param string $before_title The sidebar configured HTML that should come
* before the title itself.
* @param string $after_title The sidebar configured HTML that should come
* after the title itself.
* @param array $instance Array which contains the various settings.
* @return string The HTML for the title area
*
* @since 4.6
*/
public function titleHTML( $before_title, $after_title, $instance ) {
$ret = '';
if ( isset( $instance['title_level'] ) && in_array( $instance['title_level'], array( 'H1','H2', 'H3', 'H4', 'H5', 'H6') ) ) {
$before_title = '';
$after_title = '';
}
// If no title, use the name of the category.
if ( ! isset( $instance['title'] ) || ! $instance['title'] ) {
$instance['title'] = '';
if ( isset( $instance['cat'] ) && 0 !== (int) $instance['cat'] ) {
$category_info = get_category( $instance['cat'] );
if ( $category_info && ! is_wp_error( $category_info ) ) {
$instance['title'] = $category_info->name;
} else {
$instance['cat'] = 0; // For further processing treat it like "all categories".
$instance['title'] = __( 'Category Posts', 'category-posts' );
}
} else {
$instance['title'] = __( 'Category Posts', 'category-posts' );
}
}
$hidden = isset( $instance['hide_title'] ) && $instance['hide_title'];
$title = '';
if ( ! $hidden ) {
if ( isset( $instance['is_shortcode'] ) ) {
$title = esc_html( $instance['title'] );
} else {
$title = apply_filters( 'widget_title', $instance['title'], $instance, WIDGET_BASE_ID );
}
// Without an archive the placeholders are empty, a title left without
// text is dropped.
$title = $this->replace_archive_placeholders( (string) $title );
}
if ( '' !== trim( wp_strip_all_tags( $title ) ) ) {
$ret = $before_title;
if ( isset( $instance['title_link'] ) && $instance['title_link'] ) {
$new_tab_attr = '';
if ( ! empty( $instance['title_link_target'] ) ) {
$new_tab_attr = ' target="_blank" rel="noopener noreferrer"';
}
if ( isset( $instance['cat'] ) && 0 !== (int) $instance['cat'] ) {
$ret .= '<a href="' . get_category_link( $instance['cat'] ) . '"' . $new_tab_attr . '>' . $title . '</a>';
} elseif ( isset( $instance['title_link_url'] ) && $instance['title_link_url'] ) {
$ret .= '<a href="' . esc_url( $instance['title_link_url'] ) . '"' . $new_tab_attr . '>' . $title . '</a>';
} else {
$ret .= '<a href="' . esc_url( $this->blog_page_url() ) . '"' . $new_tab_attr . '>' . $title . '</a>';
}
} else {
$ret .= $title;
}
$ret .= $after_title;
$ret = $this->add_heading_level( $instance, $ret, 'title_level' );
}
return $ret;
}
/**
* The placeholders of the title, which stand for the page the list is on.
*
* @return string[] The placeholders.
*
* @since 5.1.3
*/
public static function archive_placeholders() {
return array( '%archive_title%', '%archive_name%' );
}
/**
* Replace the placeholders of the page the list is on in a text, see
* archive_placeholder_values().
*
* @param string $text The text, already escaped.
*
* @return string The text with the placeholders replaced.
*
* @since 5.1.3
*/
public function replace_archive_placeholders( $text ) {
$text = (string) $text;
$found = false;
foreach ( self::archive_placeholders() as $placeholder ) {
if ( false !== strpos( $text, $placeholder ) ) {
$found = true;
break;
}
}
return $found ? strtr( $text, $this->archive_placeholder_values() ) : $text;
}
/**
* The values of the placeholders of the page the list is on, as HTML.
*
* %archive_title%: the title of the archive as the theme shows it, from
* get_the_archive_title(), like "Category: News". %archive_name%: the same
* without the prefix, like "News". Empty where the page is no archive.
*
* @return string[] The values, keyed by placeholder.
*
* @since 5.1.3
*/
public function archive_placeholder_values() {
if ( $this->is_editor_preview() ) {
return $this->preview_archive_placeholder_values();
}
$values = array_fill_keys( self::archive_placeholders(), '' );
if ( is_archive() ) {
$values['%archive_title%'] = get_the_archive_title();
// The same title without prefix, so the title of every kind of archive
// still comes from core.
$no_prefix = function () {
return '';
};
add_filter( 'get_the_archive_title_prefix', $no_prefix, PHP_INT_MAX );
$values['%archive_name%'] = get_the_archive_title();
remove_filter( 'get_the_archive_title_prefix', $no_prefix, PHP_INT_MAX );
}
return $values;
}
/**
* The values of the placeholders of the page in the editor preview, which
* has no archive.
*
* They are built from what the edited template stands for, see
* preview_context(), without the filter get_the_archive_title, which needs
* the real archive. A template for one term, author or post type gets its
* title like on the front end. A template for all of them gets the kind of
* archive with "Name", like the core query title block, so it is clear the
* front end shows the term of the page there.
*
* @return string[] The values, keyed by placeholder.
*
* @since 5.1.3
*/
protected function preview_archive_placeholder_values() {
$context = $this->preview_context;
$label = ''; // The kind of archive, for templates for all of them.
$prefix = '';
$name = '';
// phpcs:disable WordPress.WP.I18n.MissingArgDomain -- The strings of core, so the preview reads like the front end.
if ( $context && 'term' === $context['type'] ) {
$term = $context['object'];
$taxonomy = get_taxonomy( $term->taxonomy );
$name = esc_html( $term->name );
if ( 'category' === $term->taxonomy ) {
$prefix = _x( 'Category:', 'category archive title prefix' );
} elseif ( 'post_tag' === $term->taxonomy ) {
$prefix = _x( 'Tag:', 'tag archive title prefix' );
} elseif ( $taxonomy ) {
/* translators: %s: Taxonomy singular name. */
$prefix = sprintf( _x( '%s:', 'taxonomy term archive title prefix' ), $taxonomy->labels->singular_name );
}
} elseif ( $context && 'author' === $context['type'] ) {
$name = esc_html( $context['object']->display_name );
$prefix = _x( 'Author:', 'author archive title prefix' );
} elseif ( preg_match( '/^archive-(.+)$/', (string) $this->preview_template_slug, $m ) && post_type_exists( $m[1] ) ) {
$name = esc_html( get_post_type_object( $m[1] )->labels->name );
$prefix = _x( 'Archives:', 'post type archive title prefix' );
} else {
$slug = (string) $this->preview_template_slug;
$taxonomy = null;
if ( 'category' === $slug || 'tag' === $slug ) {
$taxonomy = get_taxonomy( 'tag' === $slug ? 'post_tag' : 'category' );
} elseif ( 0 === strpos( $slug, 'taxonomy-' ) ) {
$taxonomy = get_taxonomy( substr( $slug, strlen( 'taxonomy-' ) ) );
}
if ( $taxonomy ) {
$label = $taxonomy->labels->singular_name;
} elseif ( 'date' === $slug ) {
$label = __( 'Date', 'category-posts' );
} elseif ( 'author' === $slug ) {
$label = __( 'Author', 'category-posts' );
}
}
if ( '' !== $name ) {
/* translators: 1: Title prefix. 2: Title. */
$title = sprintf( _x( '%1$s %2$s', 'archive title' ), esc_html( $prefix ), '<span>' . $name . '</span>' );
} elseif ( '' !== $label ) {
/* translators: %s: Kind of archive, like "Category" or "Author". */
$title = esc_html( sprintf( __( '%s: Name', 'category-posts' ), $label ) );
/* translators: %s: Kind of archive, like "Category" or "Author". */
$name = esc_html( sprintf( __( '%s name', 'category-posts' ), $label ) );
} else {
$title = esc_html__( 'Archive type: Name', 'category-posts' );
$name = esc_html__( 'Archive title', 'category-posts' );
}
// phpcs:enable WordPress.WP.I18n.MissingArgDomain
return array(
'%archive_title%' => $title,
'%archive_name%' => $name,
);
}
/**
* Add a heading level
*
* @return string The title string
*
* @since 5.0
*/
public function add_heading_level( $instance, $ret, $key ) {
$class = ( isset( $instance[ 'disable_theme_styles' ] ) && $instance[ 'disable_theme_styles' ] ) ? '' : ' class="widget-title"';
switch ( isset( $instance[ $key ] ) ? $instance[ $key ] : '' ) {
case 'H1':
$ret = '<h1' . $class . '>' . $ret . '</h1>';
break;
case 'H2':
$ret = '<h2' . $class . '>' . $ret . '</h2>';
break;
case 'H3':
$ret = '<h3' . $class . '>' . $ret . '</h3>';
break;
case 'H4':
$ret = '<h4' . $class . '>' . $ret . '</h4>';
break;
case 'H5':
$ret = '<h5' . $class . '>' . $ret . '</h5>';
break;
case 'H6':
$ret = '<h6' . $class . '>' . $ret . '</h6>';
break;
}
return $ret;
}
/**
* Get the URL of the blog page or home page if no explicit blog page is defined.
*
* @return string The URL of the blog page
*
* @since 4.8
*/
private function blog_page_url() {
$blog_page = get_option( 'page_for_posts' );
if ( $blog_page ) {
$url = get_permalink( $blog_page );
} else {
$url = home_url();
}
return $url;
}
/**
* The ID of this list as used by "load more" and the pagination, like
* 'widget-3', 'block-2' or 'shortcode-12'.
*
* @return string The ID.
*
* @since 5.1.3
*/
public function list_id() {
// We rely on the widget number to be properly set.
// but need a slight different handling for proper widgets.
if ( is_int( $this->number ) ) {
// it is a proper widget, add the prefix.
$id = 'widget-' . $this->number;
} else {
$id = str_replace( WIDGET_BASE_ID . '-', '', $this->number );
}
if ( 0 === strpos( (string) $this->number, 'block-' ) ) {
$id = 'block-' . substr( $this->number, 6 );
}
return (string) $id;
}
/**
* The name of the URL parameter holding the page of this list.
*
* Each list gets its own parameter rather than /page/N/, so several lists
* on one page are paged independently, and on a single post the page of
* the post itself (<!--nextpage-->) is not touched.
*
* @return string The parameter name, like 'cpwp-block-2-page'.
*
* @since 5.1.3
*/
public function pagination_param() {
return 'cpwp-' . $this->list_id() . '-page';
}
/**
* The page of this list requested in the URL, 1 if none.
*
* @return int The page number.
*
* @since 5.1.3
*/
public function current_page() {
$param = $this->pagination_param();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read only, public pagination.
$page = isset( $_GET[ $param ] ) ? (int) $_GET[ $param ] : 1;
return max( 1, $page );
}
/**
* Calculate the HTML of the pagination below the list.
*
* Page numbers with a previous and a next link. Relies on get_elements_HTML()
* having run for the first page of the list, it sets the current and the
* total number of pages.
*
* @param array $instance Array which contains the various settings.
*
* @return string The HTML of the pagination, empty if there is only one page.
*
* @since 5.1.3
*/
public function paginationHTML( $instance ) {
$total = (int) $this->total_pages;
$current = min( (int) $this->current_page, $total );
if ( 2 > $total ) {
return '';
}
$inherit = ! empty( $instance['inherit_query'] );
$param = $this->pagination_param();
$base = remove_query_arg( $param );
$link = function ( $page ) use ( $param, $base, $inherit ) {
if ( $inherit ) {
// The pages of the page itself, /page/N/ or ?paged=N.
return esc_url( get_pagenum_link( $page ) );
}
return esc_url( 1 === $page ? $base : add_query_arg( $param, $page, $base ) );
};
$links = paginate_links(
array(
'base' => $inherit ? str_replace( '999999999', '%#%', $link( 999999999 ) ) : add_query_arg( $param, '%#%', $base ),
'format' => '',
'current' => $current,
'total' => $total,
'prev_text' => esc_html__( '« Previous', 'category-posts' ),
'next_text' => esc_html__( 'Next »', 'category-posts' ),
)
);
// paginate_links() builds the link to the first page from the base too,
// the first page has no parameter.
$first = $inherit ? str_replace( '999999999', '1', $link( 999999999 ) ) : esc_url( add_query_arg( $param, 1, $base ) );
$links = str_replace( '"' . $first . '"', '"' . $link( 1 ) . '"', $links );
return '<nav class="' . __NAMESPACE__ . '-pagination" aria-label="' . esc_attr__( 'Posts pagination', 'category-posts' ) . '">' .
$links .
'</nav>';
}
/**
* Whether the list is rendered for the editor preview, a REST request
* without a page of its own.
*
* @return bool True in the editor preview.
*
* @since 5.1.3
*/
protected function is_editor_preview() {
return defined( 'REST_REQUEST' ) && REST_REQUEST;
}
/**
* The query type of a list: 'custom', 'default' (the query of the page) or
* 'context' ("Matching": the category of the page, with the query of the list).
*
* @param array $instance Array which contains the various settings.
*
* @return string The query type.
*
* @since 5.1.3
*/
public function query_type( $instance ) {
if ( isset( $instance['query_type'] ) && in_array( $instance['query_type'], array( 'custom', 'default', 'context' ), true ) ) {
return $instance['query_type'];
}
return empty( $instance['inherit_query'] ) ? 'custom' : 'default';
}
/**
* What a list with "Query type: Matching" can take from the page it is on.
*
* With a current post (a single post page, an entry of a Query Loop, the
* post of the editor preview) its categories, see post_context_vars().
* Without, the category of a category archive, see page_context_vars().
*
* @param int|string $singular_id The current post, 0 or empty if none.
*
* @return array The context, see page_context_vars().
*
* @since 5.1.3
*/
public function context_vars( $singular_id = 0 ) {
$singular_id = (int) $singular_id;
if ( 0 < $singular_id ) {
$post = get_post( $singular_id );
// The ID may come from the client ("load more"), drafts only for those
// who may read them, like in the editor preview.
if ( $post && ( ( 'publish' === $post->post_status && is_post_type_viewable( $post->post_type ) )
|| current_user_can( 'read_post', $post->ID ) ) ) {
return $this->post_context_vars( $post );
}
}
if ( null !== $this->page_context ) {
return $this->page_context;
}
if ( $this->is_editor_preview() ) {
return $this->preview_page_context_vars();
}
return $this->page_context_vars();
}
/**
* What a post has: its categories. The post itself is left out of the list.
*
* @param \WP_Post $post The post.
*
* @return array The context, see page_context_vars().
*
* @since 5.1.3
*/
public function post_context_vars( $post ) {
$cats = array();
if ( is_object_in_taxonomy( $post->post_type, 'category' ) ) {
$terms = wp_get_object_terms( $post->ID, 'category', array( 'fields' => 'ids' ) );
$cats = is_wp_error( $terms ) ? array() : array_map( 'intval', $terms );
}
return array(
'singular' => true,
'cat' => $cats,
'exclude' => (int) $post->ID,
);
}
/**
* What the page the list is shown on is about: the category of a category
* archive. Tags, custom taxonomies, authors, dates and the search are left
* to the Pro version.
*
* @return array Array with 'singular' (false), 'cat' (category IDs, empty
* if none) and, for a post, 'exclude'.
*
* @since 5.1.3
*/
public function page_context_vars() {
$vars = array(
'singular' => false,
'cat' => array(),
);
if ( is_category() ) {
$term = get_queried_object();
if ( $term instanceof \WP_Term ) {
$vars['cat'] = array( (int) $term->term_id );
}
}
return $vars;
}
/**
* What the page the edited template stands for is about, for the editor
* preview, see preview_context(): the category of a template for one
* category. Templates for all categories stand for nothing in particular.
*
* @return array The context, see page_context_vars().
*
* @since 5.1.3
*/
public function preview_page_context_vars() {
$context = $this->preview_context;
$vars = array(
'singular' => false,
'cat' => array(),
);
if ( $context && 'term' === $context['type'] && 'category' === $context['object']->taxonomy ) {
$vars['cat'] = array( (int) $context['object']->term_id );
}
return $vars;
}
/**
* The fields chosen under "Match by": 'tax:category' or none. Without a
* choice stored, the category.
*
* @param array $instance Array which contains the various settings.
*
* @return string[] The fields.
*
* @since 5.1.3
*/
public function context_fields( $instance ) {
if ( isset( $instance['context_same'] ) && is_array( $instance['context_same'] ) ) {
return array_values( array_map( 'strval', $instance['context_same'] ) );
}
return array( 'tax:category' );
}
/**
* The settings of a list with "Query type: Matching" for its own query.
*
* The category is not a filter then, it comes from the page.
*
* @param array $instance Array which contains the various settings.
*
* @return array The settings.
*
* @since 5.1.3
*/
public function context_query_instance( $instance ) {
unset( $instance['cat'] );
return $instance;
}
/**
* Limit the query of a list to what it takes from the page.
*
* The categories of the page count only with "Match by: Category", and only
* when the page has any. Several categories of a post: one of them.
* "Exclude child categories" holds for the categories from the page. On a
* single post the post itself is left out.
*
* @param array $args The query arguments of the list, see queryArgs().
* @param array|false $vars The context, see page_context_vars(), false if
* it is not known.
* @param array $instance Array which contains the various settings.
*