forked from johnbillion/extended-cpts
/
extended-cpts.php
executable file
·2214 lines (1851 loc) · 70.2 KB
/
extended-cpts.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
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
/*
Plugin Name: Extended CPTs
Description: Extended custom post types.
Version: 2.5.1
Plugin URI: https://github.com/johnbillion/extended-cpts
Author: John Blackbourn
Author URI: https://johnblackbourn.com
Text Domain: extended-cpts
Domain Path: /languages/
License: GPL v2 or later
Copyright © 2012-2015 John Blackbourn
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
if ( ! function_exists( 'register_extended_post_type' ) ) {
/**
* Register an Extended Post Type.
*
* The `$args` parameter accepts all the standard arguments for `register_post_type()` in addition to several custom
* arguments that provide extended functionality. Some of the default arguments differ from the defaults in
* `register_post_type()`.
*
* The `$post_type` parameter is used as the post type name and to build the post type labels. This means you can create
* a post type with just one parameter and all labels and post updated messages will be generated for you. Example:
*
* register_extended_post_type( 'event' );
*
* The singular name, plural name, and slug are generated from the post type name. These can be overridden with the
* `$names` parameter if necessary. Example:
*
* register_extended_post_type( 'person', array(), array(
* 'plural' => 'People',
* 'slug' => 'meet-the-team'
* ) );
*
* @see register_post_type() for default arguments.
*
* @param string $post_type The post type name.
* @param array $args {
* Optional. The post type arguments.
*
* @type array $admin_cols Associative array of admin screen columns to show for this post type.
* @type array $admin_filters Associative array of admin screen filters to show for this post type.
* @type array $archive Associative array of query vars to override on this post type's archive.
* @type bool $dashboard_glance Whether to show this post type on the 'At a Glance' section of the admin
* dashboard. Default true.
* @type string $enter_title_here Placeholder text which appears in the title field for this post type.
* @type string $featured_image Text which replaces the 'Featured Image' phrase for this post type.
* @type bool $quick_edit Whether to show Quick Edit links for this post type. Default true.
* @type bool $show_in_feed Whether to include this post type in the site's main feed. Default false.
* @type array $site_filters Associative array of query vars and their parameters for front end filtering.
* @type array $site_sortables Associative array of query vars and their parameters for front end sorting.
* }
* @param array $names {
* Optional. The plural, singular, and slug names.
*
* @type string $plural The plural form of the post type name.
* @type string $singular The singular form of the post type name.
* @type string $slug The slug used in the permalinks for this post type.
* }
* @return Extended_CPT
*/
function register_extended_post_type( $post_type, array $args = array(), array $names = array() ) {
$cpt = new Extended_CPT( $post_type, $args, $names );
if ( is_admin() ) {
new Extended_CPT_Admin( $cpt, $args );
}
return $cpt;
}
}
if ( ! class_exists( 'Extended_CPT' ) ) {
class Extended_CPT {
/**
* Default arguments for custom post types.
*
* The arguments listed are the ones which differ from the defaults in `register_post_type()`.
*
* @var array
*/
protected $defaults = array(
'public' => true,
'menu_position' => 6,
'capability_type' => 'page',
'hierarchical' => true,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'site_filters' => null, # Custom arg
'site_sortables' => null, # Custom arg
'show_in_feed' => false, # Custom arg
'archive' => null, # Custom arg
'featured_image' => null, # Custom arg
);
/**
* Some other member variables you don't need to worry about:
*/
public $post_type;
public $post_slug;
public $post_singular;
public $post_plural;
public $post_singular_low;
public $post_plural_low;
public $args;
protected $_cols;
/**
* Class constructor.
*
* @param string $post_type The post type name.
* @param array $args Optional. The post type arguments. {@see register_extended_post_type()}.
* @param array $names Optional. The plural, singular, and slug names. {@see register_extended_post_type()}.
*/
public function __construct( $post_type, array $args = array(), array $names = array() ) {
/**
* Filter the arguments for this post type.
*
* @since 2.4.0
* @param array $args The post type arguments.
*/
$args = apply_filters( "ext-cpts/{$post_type}/args", $args );
/**
* Filter the names for this post type.
*
* @since 2.4.0
* @param array $names The plural, singular, and slug names (if any were specified).
*/
$names = apply_filters( "ext-cpts/{$post_type}/names", $names );
if ( isset( $names['singular'] ) ) {
$this->post_singular = $names['singular'];
} else {
$this->post_singular = ucwords( str_replace( array( '-', '_' ), ' ', $post_type ) );
}
if ( isset( $names['slug'] ) ) {
$this->post_slug = $names['slug'];
} else if ( isset( $names['plural'] ) ) {
$this->post_slug = $names['plural'];
} else {
$this->post_slug = $post_type . 's';
}
if ( isset( $names['plural'] ) ) {
$this->post_plural = $names['plural'];
} else {
$this->post_plural = $this->post_singular . 's';
}
$this->post_type = strtolower( $post_type );
$this->post_slug = strtolower( $this->post_slug );
# Build our base post type names:
$this->post_singular_low = strtolower( $this->post_singular );
$this->post_plural_low = strtolower( $this->post_plural );
# Build our labels:
# Why aren't these translatable?
# Answer: https://github.com/johnbillion/extended-cpts/pull/5#issuecomment-33756474
$this->defaults['labels'] = array(
'name' => $this->post_plural,
'singular_name' => $this->post_singular,
'menu_name' => $this->post_plural,
'name_admin_bar' => $this->post_singular,
'add_new' => 'Add New',
'add_new_item' => sprintf( 'Add New %s', $this->post_singular ),
'edit_item' => sprintf( 'Edit %s', $this->post_singular ),
'new_item' => sprintf( 'New %s', $this->post_singular ),
'view_item' => sprintf( 'View %s', $this->post_singular ),
'search_items' => sprintf( 'Search %s', $this->post_plural ),
'not_found' => sprintf( 'No %s found.', $this->post_plural_low ),
'not_found_in_trash' => sprintf( 'No %s found in trash.', $this->post_plural_low ),
'parent_item_colon' => sprintf( 'Parent %s:', $this->post_singular ),
'all_items' => sprintf( 'All %s', $this->post_plural ),
'archives' => sprintf( '%s Archives', $this->post_singular ),
'insert_into_item' => sprintf( 'Insert into %s', $this->post_singular_low ),
'uploaded_to_this_item' => sprintf( 'Uploaded to this %s', $this->post_singular_low ),
'filter_items_list' => sprintf( 'Filter %s list', $this->post_plural_low ),
'items_list_navigation' => sprintf( '%s list navigation', $this->post_plural ),
'items_list' => sprintf( '%s list', $this->post_plural ),
);
# Build the featured image labels:
if ( isset( $args['featured_image'] ) ) {
$featured_image_low = strtolower( $args['featured_image'] );
$this->defaults['labels']['featured_image'] = $args['featured_image'];
$this->defaults['labels']['set_featured_image'] = sprintf( 'Set %s', $featured_image_low );
$this->defaults['labels']['remove_featured_image'] = sprintf( 'Remove %s', $featured_image_low );
$this->defaults['labels']['use_featured_image'] = sprintf( 'Use as %s', $featured_image_low );
}
# Only set default rewrites if we need them
if ( isset( $args['public'] ) && ! $args['public'] ) {
$this->defaults['rewrite'] = false;
} else {
$this->defaults['rewrite'] = array(
'slug' => $this->post_slug,
'with_front' => false,
);
}
# Merge our args with the defaults:
$this->args = array_merge( $this->defaults, $args );
# This allows the 'labels' and 'rewrite' args to contain all, some, or no values:
foreach ( array( 'labels', 'rewrite' ) as $arg ) {
if ( isset( $args[ $arg ] ) && is_array( $args[ $arg ] ) ) {
$this->args[ $arg ] = array_merge( $this->defaults[ $arg ], $args[ $arg ] );
}
}
# Enable post type archives by default
if ( ! isset( $this->args['has_archive'] ) ) {
$this->args['has_archive'] = $this->args['public'];
}
# Front-end sortables:
if ( $this->args['site_sortables'] && ! is_admin() ) {
add_filter( 'pre_get_posts', array( $this, 'maybe_sort_by_fields' ) );
add_filter( 'posts_clauses', array( $this, 'maybe_sort_by_taxonomy' ), 10, 2 );
}
# Front-end filters:
if ( $this->args['site_filters'] && ! is_admin() ) {
add_action( 'pre_get_posts', array( $this, 'maybe_filter' ) );
add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
}
# Post type in the site's main feed:
if ( $this->args['show_in_feed'] ) {
add_filter( 'request', array( $this, 'add_to_feed' ) );
}
# Post type archive query vars:
if ( $this->args['archive'] && ! is_admin() ) {
add_filter( 'parse_request', array( $this, 'override_private_query_vars' ), 1 );
}
# Custom post type permastruct:
if ( $this->args['rewrite'] && ! empty( $this->args['rewrite']['permastruct'] ) ) {
add_action( 'registered_post_type', array( $this, 'registered_post_type' ), 1, 2 );
add_filter( 'post_type_link', array( $this, 'post_type_link' ), 1, 4 );
}
# Rewrite testing:
if ( $this->args['rewrite'] ) {
add_filter( 'rewrite_testing_tests', array( $this, 'rewrite_testing_tests' ), 1 );
}
# Register post type when WordPress initialises:
if ( did_action( 'init' ) ) {
$this->register_post_type();
} else {
// @codeCoverageIgnoreStart
add_action( 'init', array( $this, 'register_post_type' ), 9 );
// @codeCoverageIgnoreEnd
}
}
/**
* Set the relevant query vars for filtering posts by our front-end filters.
*
* @param WP_Query $wp_query The current WP_Query object.
*/
public function maybe_filter( WP_Query $wp_query ) {
if ( empty( $wp_query->query['post_type'] ) || ! in_array( $this->post_type, (array) $wp_query->query['post_type'] ) ) {
return;
}
$vars = Extended_CPT::get_filter_vars( $wp_query->query, $this->args['site_filters'] );
if ( empty( $vars ) ) {
return;
}
foreach ( $vars as $key => $value ) {
if ( is_array( $value ) ) {
$query = $wp_query->get( $key );
if ( empty( $query ) ) {
$query = array();
}
$value = array_merge( $query, $value );
}
$wp_query->set( $key, $value );
}
}
/**
* Set the relevant query vars for sorting posts by our front-end sortables.
*
* @param WP_Query $wp_query The current WP_Query object.
*/
public function maybe_sort_by_fields( WP_Query $wp_query ) {
if ( empty( $wp_query->query['post_type'] ) || ! in_array( $this->post_type, (array) $wp_query->query['post_type'] ) ) {
return;
}
// If we've not specified an order:
if ( empty( $wp_query->query['orderby'] ) ) {
// Loop over our sortables to find the default sort field (if there is one):
foreach ( $this->args['site_sortables'] as $id => $col ) {
if ( is_array( $col ) && isset( $col['default'] ) ) {
// @TODO Don't set 'order' if 'orderby' is an array (WP 4.0+)
$wp_query->query['orderby'] = $id;
$wp_query->query['order'] = ( 'desc' == strtolower( $col['default'] ) ? 'desc' : 'asc' );
break;
}
}
}
$sort = Extended_CPT::get_sort_field_vars( $wp_query->query, $this->args['site_sortables'] );
if ( empty( $sort ) ) {
return;
}
foreach ( $sort as $key => $value ) {
$wp_query->set( $key, $value );
}
}
/**
* Filter the query's SQL clauses so we can sort posts by taxonomy terms.
*
* @param array $clauses The current query's SQL clauses.
* @param WP_Query $wp_query The current `WP_Query` object.
* @return array The updated SQL clauses.
*/
public function maybe_sort_by_taxonomy( array $clauses, WP_Query $wp_query ) {
if ( empty( $wp_query->query['post_type'] ) || ! in_array( $this->post_type, (array) $wp_query->query['post_type'] ) ) {
return $clauses;
}
$sort = Extended_CPT::get_sort_taxonomy_clauses( $clauses, $wp_query->query, $this->args['site_sortables'] );
if ( empty( $sort ) ) {
return $clauses;
}
return array_merge( $clauses, $sort );
}
/**
* Get the array of private query vars for the given filters, to apply to the current query in order to filter it by the
* given public query vars.
*
* @param array $query The public query vars, usually from `$wp_query->query`.
* @param array $filters The filters valid for this query (usually the value of the `admin_filters` or
* `site_filters` argument when registering an extended post type).
* @return array The list of private query vars to apply to the query.
*/
public static function get_filter_vars( array $query, array $filters ) {
$return = array();
foreach ( $filters as $filter_key => $filter ) {
if ( ! isset( $query[ $filter_key ] ) || ( '' === $query[ $filter_key ] ) ) {
continue;
}
if ( isset( $filter['cap'] ) && ! current_user_can( $filter['cap'] ) ) {
continue;
}
if ( isset( $filter['meta_key'] ) ) {
$meta_query = array(
'key' => $filter['meta_key'],
'value' => stripslashes( $query[ $filter_key ] ),
);
} else if ( isset( $filter['meta_search_key'] ) ) {
$meta_query = array(
'key' => $filter['meta_search_key'],
'value' => stripslashes( $query[ $filter_key ] ),
'compare' => 'LIKE',
);
} else if ( isset( $filter['meta_exists'] ) ) {
$meta_query = array(
'key' => stripslashes( $query[ $filter_key ] ),
'compare' => 'NOT IN',
'value' => array( '', '0', 'false', 'null' ),
);
} else {
continue;
}
foreach ( array( 'compare', 'value', 'type' ) as $arg ) {
if ( isset( $filter[ "meta_{$arg}" ] ) ) {
_doing_it_wrong( 'register_extended_post_type', sprintf(
__( 'The %1$s parameter for filters is deprecated. Use %2$s instead.', 'extended-cpts' ),
"<code>meta_{$arg}</code>",
"<code>meta_query['{$arg}']</code>"
), '2.4' );
$filter['meta_query'][ $arg ] = $filter[ "meta_{$arg}" ];
}
}
if ( isset( $filter['meta_query'] ) ) {
$meta_query = array_merge( $meta_query, $filter['meta_query'] );
}
if ( ! empty( $meta_query ) ) {
$return['meta_query'][] = $meta_query;
}
}
return $return;
}
/**
* Get the array of private and public query vars for the given sortables, to apply to the current query in order to
* sort it by the requested orderby field.
*
* @param array $vars The public query vars, usually from `$wp_query->query`.
* @param array $sortables The sortables valid for this query (usually the value of the `admin_cols` or
* `site_sortables` argument when registering an extended post type.
* @return array The list of private and public query vars to apply to the query.
*/
public static function get_sort_field_vars( array $vars, array $sortables ) {
if ( ! isset( $vars['orderby'] ) ) {
return array();
}
if ( ! isset( $sortables[ $vars['orderby'] ] ) ) {
return array();
}
$orderby = $sortables[ $vars['orderby'] ];
if ( ! is_array( $orderby ) ) {
return array();
}
if ( isset( $orderby['sortable'] ) && ! $orderby['sortable'] ) {
return array();
}
$return = array();
if ( isset( $orderby['meta_key'] ) ) {
$return['meta_key'] = $orderby['meta_key'];
$return['orderby'] = 'meta_value';
// @TODO meta_value_num
} else if ( isset( $orderby['post_field'] ) ) {
$field = str_replace( 'post_', '', $orderby['post_field'] );
$return['orderby'] = $field;
}
if ( isset( $vars['order'] ) ) {
$return['order'] = $vars['order'];
}
return $return;
}
/**
* Get the array of SQL clauses for the given sortables, to apply to the current query in order to
* sort it by the requested orderby field.
*
* @param array $clauses The query's SQL clauses.
* @param array $vars The public query vars, usually from `$wp_query->query`.
* @param array $sortables The sortables valid for this query (usually the value of the `admin_cols` or
* `site_sortables` argument when registering an extended post type).
* @return array The list of SQL clauses to apply to the query.
*/
public static function get_sort_taxonomy_clauses( array $clauses, array $vars, array $sortables ) {
global $wpdb;
if ( ! isset( $vars['orderby'] ) ) {
return array();
}
if ( ! isset( $sortables[ $vars['orderby'] ] ) ) {
return array();
}
$orderby = $sortables[ $vars['orderby'] ];
if ( ! is_array( $orderby ) ) {
return array();
}
if ( isset( $orderby['sortable'] ) && ! $orderby['sortable'] ) {
return array();
}
if ( ! isset( $orderby['taxonomy'] ) ) {
return array();
}
# Taxonomy term ordering courtesy of http://scribu.net/wordpress/sortable-taxonomy-columns.html
$clauses['join'] .= "
LEFT OUTER JOIN {$wpdb->term_relationships} as ext_cpts_tr
ON ( {$wpdb->posts}.ID = ext_cpts_tr.object_id )
LEFT OUTER JOIN {$wpdb->term_taxonomy} as ext_cpts_tt
ON ( ext_cpts_tr.term_taxonomy_id = ext_cpts_tt.term_taxonomy_id )
LEFT OUTER JOIN {$wpdb->terms} as ext_cpts_t
ON ( ext_cpts_tt.term_id = ext_cpts_t.term_id )
";
$clauses['where'] .= $wpdb->prepare( ' AND ( taxonomy = %s OR taxonomy IS NULL )', $orderby['taxonomy'] );
$clauses['groupby'] = 'ext_cpts_tr.object_id';
$clauses['orderby'] = 'GROUP_CONCAT( ext_cpts_t.name ORDER BY name ASC ) ';
$clauses['orderby'] .= ( isset( $vars['order'] ) && ( 'ASC' == strtoupper( $vars['order'] ) ) ) ? 'ASC' : 'DESC';
return $clauses;
}
/**
* Add our filter names to the public query vars.
*
* @param array $vars Public query variables.
* @return array Updated public query variables.
*/
public function add_query_vars( array $vars ) {
$filters = array_keys( $this->args['site_filters'] );
return array_merge( $vars, $filters );
}
/**
* Add our post type to the feed.
*
* @param array $vars Request parameters.
* @return array Updated request parameters.
*/
public function add_to_feed( array $vars ) {
# If it's not a feed, we're not interested:
if ( ! isset( $vars['feed'] ) ) {
return $vars;
}
if ( ! isset( $vars['post_type'] ) ) {
$vars['post_type'] = array( 'post', $this->post_type );
} else if ( is_array( $vars['post_type'] ) && ( count( $vars['post_type'] ) > 1 ) ) {
$vars['post_type'][] = $this->post_type;
}
return $vars;
}
/**
* Add to or override our post type archive's private query vars.
*
* @param WP $wp The WP request object.
* @return WP Updated WP request object.
*/
public function override_private_query_vars( WP $wp ) {
# If it's not our post type, bail out:
if ( ! isset( $wp->query_vars['post_type'] ) || ( $this->post_type != $wp->query_vars['post_type'] ) ) {
return $wp;
}
# If it's a single post, bail out:
if ( isset( $wp->query_vars['name'] ) ) {
return $wp;
}
# Set the vars:
foreach ( $this->args['archive'] as $var => $value ) {
$wp->query_vars[ $var ] = $value;
}
return $wp;
}
/**
* Action fired after a CPT is registered in order to set up the custom permalink structure for the post type.
*
* @param string $post_type Post type name.
* @param object $args Arguments used to register the post type.
*/
public function registered_post_type( $post_type, stdClass $args ) {
if ( $post_type != $this->post_type ) {
return;
}
$struct = str_replace( "%{$this->post_type}_slug%", $this->post_slug, $args->rewrite['permastruct'] );
$struct = str_replace( '%postname%', "%{$this->post_type}%", $struct );
add_permastruct( $this->post_type, $struct, $args->rewrite );
}
/**
* Filter the post type permalink in order to populate its rewrite tags.
*
* @param string $post_link The post's permalink.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
* @param bool $sample Is it a sample permalink.
* @return string The post's permalink.
*/
public function post_type_link( $post_link, WP_Post $post, $leavename, $sample ) {
# If it's not our post type, bail out:
if ( $this->post_type != $post->post_type ) {
return $post_link;
}
$date = explode( ' ', mysql2date( 'Y m d H i s', $post->post_date ) );
$replacements = array(
'%year%' => $date[0],
'%monthnum%' => $date[1],
'%day%' => $date[2],
'%hour%' => $date[3],
'%minute%' => $date[4],
'%second%' => $date[5],
'%post_id%' => $post->ID,
);
if ( false !== strpos( $post_link, '%author%' ) ) {
$replacements['%author%'] = get_userdata( $post->post_author )->user_nicename;
}
foreach ( get_object_taxonomies( $post ) as $tax ) {
if ( false === strpos( $post_link, "%{$tax}%" ) ) {
continue;
}
if ( $terms = get_the_terms( $post, $tax ) ) {
/**
* Filter the term that gets used in the `$tax` permalink token.
* @TODO make this more betterer ^
*
* @param stdClass $term The `$tax` term to use in the permalink.
* @param array $terms Array of all `$tax` terms associated with the post.
* @param WP_Post $post The post in question.
*/
$term_object = apply_filters( "post_link_{$tax}", reset( $terms ), $terms, $post );
$term = get_term( $term_object, $tax )->slug;
} else {
$term = $post->post_type;
/**
* Filter the default term name that gets used in the `$tax` permalink token.
* @TODO make this more betterer ^
*
* @param string $term The `$tax` term name to use in the permalink.
* @param WP_Post $post The post in question.
*/
$default_term_name = apply_filters( "default_{$tax}", get_option( "default_{$tax}" ), $post );
if ( $default_term_name ) {
if ( ! is_wp_error( $default_term = get_term( $default_term_name, $tax ) ) ) {
$term = $default_term->slug;
}
}
}
$replacements[ "%{$tax}%" ] = $term;
}
$post_link = str_replace( array_keys( $replacements ), $replacements, $post_link );
return $post_link;
}
/**
* Add our rewrite tests to the Rewrite Rule Testing tests array.
*
* @codeCoverageIgnore
*
* @param array $tests The existing rewrite rule tests.
* @return array Updated rewrite rule tests.
*/
public function rewrite_testing_tests( array $tests ) {
$extended = new Extended_CPT_Rewrite_Testing( $this );
return array_merge( $tests, $extended->get_tests() );
}
/**
* Registers our post type.
*
* The only difference between this and regular `register_post_type()` calls is this will trigger an error of
* `E_USER_ERROR` level if a `WP_Error` is returned.
*
*/
public function register_post_type() {
if ( ! isset( $this->args['query_var'] ) || ( true === $this->args['query_var'] ) ) {
$query_var = $this->post_type;
} else {
$query_var = $this->args['query_var'];
}
$existing = get_post_type_object( $this->post_type );
if ( $query_var && count( get_taxonomies( array( 'query_var' => $query_var ) ) ) ) {
trigger_error( sprintf( __( 'Post type query var %s clashes with a taxonomy query var of the same name', 'extended-cpts' ), "<code>{$query_var}</code>" ), E_USER_ERROR );
} else if ( empty( $existing ) ) {
$cpt = register_post_type( $this->post_type, $this->args );
if ( is_wp_error( $cpt ) ) {
trigger_error( $cpt->get_error_message(), E_USER_ERROR );
}
} else {
# This allows us to call `register_extended_post_type()` on an existing post type to add custom functionality
# to the post type.
$this->extend( $existing );
}
}
/**
* Extends an existing post type object. Currently only handles labels.
*
* @param object $pto A post type object
*/
public function extend( stdClass $pto ) {
$GLOBALS['wp_post_types'][ $pto->name ]->labels = (object) $this->args['labels'];
}
/**
* Helper function for registering a taxonomy and adding it to this post type.
*
* Accepts the same parameters as `register_extended_taxonomy()`, minus the `$object_type` parameter. Will fall back
* to `register_taxonomy()` if Extended Taxonomies isn't present.
*
* Example usage:
*
* $events = register_extended_post_type( 'event' );
* $location = $events->add_taxonomy( 'location' );
*
* @param string $taxonomy The taxonomy name.
* @param array $args Optional. The taxonomy arguments.
* @param array $names Optional. An associative array of the plural, singular, and slug names.
* @return object|false Taxonomy object, or boolean false if there's a problem.
*/
public function add_taxonomy( $taxonomy, array $args = array(), array $names = array() ) {
if ( taxonomy_exists( $taxonomy ) ) {
register_taxonomy_for_object_type( $taxonomy, $this->post_type );
} else if ( function_exists( 'register_extended_taxonomy' ) ) {
register_extended_taxonomy( $taxonomy, $this->post_type, $args, $names );
} else {
register_taxonomy( $taxonomy, $this->post_type, $args );
}
return get_taxonomy( $taxonomy );
}
}
}
if ( ! class_exists( 'Extended_CPT_Admin' ) ) {
class Extended_CPT_Admin {
/**
* Default arguments for custom post types.
*
* @var array
*/
protected $defaults = array(
'quick_edit' => true, # Custom arg
'dashboard_glance' => true, # Custom arg
'admin_cols' => null, # Custom arg
'admin_filters' => null, # Custom arg
'enter_title_here' => null, # Custom arg
);
public $cpt;
public $args;
protected $_cols;
protected $the_cols = null;
protected $connection_exists = array();
/**
* Class constructor.
*
* @param Extended_CPT $cpt An extended post type object.
* @param array $args Optional. The post type arguments.
*/
public function __construct( Extended_CPT $cpt, array $args = array() ) {
$this->cpt = $cpt;
# Merge our args with the defaults:
$this->args = array_merge( $this->defaults, $args );
# Admin columns:
if ( isset( $this->args['cols'] ) ) {
_doing_it_wrong( 'register_extended_post_type', sprintf(
__( 'The %1$s argument is deprecated. Use %2$s instead.', 'extended-cpts' ),
'<code>cols</code>',
'<code>admin_cols</code>'
), '2.4' );
$this->args['admin_cols'] = $this->args['cols'];
}
if ( $this->args['admin_cols'] ) {
add_filter( 'manage_posts_columns', array( $this, '_log_default_cols' ), 0 );
add_filter( 'manage_pages_columns', array( $this, '_log_default_cols' ), 0 );
add_filter( "manage_edit-{$this->cpt->post_type}_sortable_columns", array( $this, 'sortables' ) );
add_filter( "manage_{$this->cpt->post_type}_posts_columns", array( $this, 'cols' ) );
add_action( "manage_{$this->cpt->post_type}_posts_custom_column", array( $this, 'col' ) );
add_action( 'load-edit.php', array( $this, 'default_sort' ) );
add_filter( 'pre_get_posts', array( $this, 'maybe_sort_by_fields' ) );
add_filter( 'posts_clauses', array( $this, 'maybe_sort_by_taxonomy' ), 10, 2 );
}
# Admin filters:
if ( isset( $this->args['filters'] ) ) {
_doing_it_wrong( 'register_extended_post_type', sprintf(
__( 'The %1$s argument is deprecated. Use %2$s instead.', 'extended-cpts' ),
'<code>filters</code>',
'<code>admin_filters</code>'
), '2.4' );
$this->args['admin_filters'] = $this->args['filters'];
}
if ( $this->args['admin_filters'] ) {
add_filter( 'pre_get_posts', array( $this, 'maybe_filter' ) );
add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
add_action( 'restrict_manage_posts', array( $this, 'filters' ) );
}
# 'Enter title here' filter:
if ( $this->args['enter_title_here'] ) {
add_filter( 'enter_title_here', array( $this, 'enter_title_here' ), 10, 2 );
}
# Hide month filter:
if ( isset( $this->args['admin_filters']['m'] ) && ! $this->args['admin_filters']['m'] ) {
add_action( 'admin_head-edit.php', array( $this, 'admin_head' ) );
}
# Quick Edit:
if ( ! $this->args['quick_edit'] ) {
add_filter( 'post_row_actions', array( $this, 'remove_quick_edit_action' ), 10, 2 );
add_filter( 'page_row_actions', array( $this, 'remove_quick_edit_action' ), 10, 2 );
add_filter( "bulk_actions-edit-{$this->cpt->post_type}", array( $this, 'remove_quick_edit_menu' ) );
}
# 'At a Glance' dashboard panels:
if ( isset( $this->args['right_now'] ) ) {
_doing_it_wrong( 'register_extended_post_type', sprintf(
__( 'The %1$s argument is deprecated. Use %2$s instead.', 'extended-cpts' ),
'<code>right_now</code>',
'<code>dashboard_glance</code>'
), '2.4' );
$this->args['dashboard_glance'] = $this->args['right_now'];
}
if ( $this->args['dashboard_glance'] ) {
add_filter( 'dashboard_glance_items', array( $this, 'glance_items' ), $this->cpt->args['menu_position'] );
}
# Nav menus screen item:
if ( $this->cpt->args['has_archive'] ) {
add_filter( "nav_menu_items_{$this->cpt->post_type}", array( $this, 'nav_menu_items' ), 10, 3 );
}
# Post updated messages:
add_filter( 'post_updated_messages', array( $this, 'post_updated_messages' ), 1 );
add_filter( 'bulk_post_updated_messages', array( $this, 'bulk_post_updated_messages' ), 1, 2 );
}
/**
* Add some CSS to the post edit screen. Used to hide various screen elements.
*/
public function admin_head() {
if ( $this->cpt->post_type != self::get_current_post_type() ) {
return;
}
?>
<?php if ( isset( $this->args['admin_filters']['m'] ) && ! $this->args['admin_filters']['m'] ) { ?>
<style type="text/css">
#posts-filter select[name="m"] {
display: none;
}
</style>
<?php } ?>
<?php
}
/**
* Set the default sort field and sort order on our post type admin screen.
*/
public function default_sort() {
if ( $this->cpt->post_type != self::get_current_post_type() ) {
return;
}
# If we've already ordered the screen, bail out:
if ( isset( $_GET['orderby'] ) ) {
return;
}
# Loop over our columns to find the default sort column (if there is one):
foreach ( $this->args['admin_cols'] as $id => $col ) {
if ( is_array( $col ) && isset( $col['default'] ) ) {
$_GET['orderby'] = $id;
$_GET['order'] = ( 'desc' == strtolower( $col['default'] ) ? 'desc' : 'asc' );
break;
}
}
}
/**
* Set the placeholder text for the title field for this post type.
*
* @param string $title The placeholder text.
* @param WP_Post $post The current post.
* @return string The updated placeholder text.
*/
public function enter_title_here( $title, WP_Post $post ) {
if ( $this->cpt->post_type != $post->post_type ) {
return $title;
}
return $this->args['enter_title_here'];
}
/**
* Returns the name of the post type for the current request.
*
* @return string The post type name.
*/
protected static function get_current_post_type() {
if ( function_exists( 'get_current_screen' ) && is_object( get_current_screen() ) ) {
$post_type = get_current_screen()->post_type;
} else {
$post_type = '';
}
if ( empty( $post_type ) ) {
if ( isset( $_REQUEST['post_type'] ) ) {
$post_type = $_REQUEST['post_type'];
} else if ( isset( $_REQUEST['post'] ) ) {
$post_type = get_post_type( $_REQUEST['post'] );
} else if ( isset( $_REQUEST['post_id'] ) ) {
$post_type = get_post_type( $_REQUEST['post_id'] );
} else if ( isset( $_REQUEST['attachment_id'] ) ) {
$post_type = get_post_type( get_post( $_REQUEST['attachment_id'] )->post_parent );
}
}
return $post_type;
}
/**
* Output custom filter dropdown menus on the admin screen for this post type.
*
* Each item in the `admin_filters` array is an associative array of information for a filter. Defining a filter is
* easy. Just define an array which includes the filter title and filter type. You can display filters for post meta
* fields and taxonomy terms.
*
* The example below adds filters for the `event_type` meta key and the `location` taxonomy:
*
* register_extended_post_type( 'event', array(
* 'admin_filters' => array(
* 'event_type' => array(
* 'title' => 'Event Type',
* 'meta_key' => 'event_type'
* ),