forked from WebDevStudios/Taxonomy_Single_Term
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.taxonomy-single-term.php
658 lines (566 loc) · 18.9 KB
/
class.taxonomy-single-term.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
<?php
if ( ! class_exists( 'Taxonomy_Single_Term' ) ) :
/**
* Removes and replaces the built-in taxonomy metabox with <select> or series of <input type="radio" />
*
* Usage:
*
* $custom_tax_mb = new Taxonomy_Single_Term( 'custom-tax-slug', array( 'post_type' ), 'type' ); // 'type' can be 'radio' or 'select' (default: radio)
*
* Update optional properties:
*
* $custom_tax_mb->set( 'priority', 'low' );
* $custom_tax_mb->set( 'context', 'normal' );
* $custom_tax_mb->set( 'metabox_title', __( 'Custom Metabox Title', 'yourtheme' ) );
* $custom_tax_mb->set( 'force_selection', true );
* $custom_tax_mb->set( 'indented', false );
* $custom_tax_mb->set( 'allow_new_terms', true );
*
* @link http://codex.wordpress.org/Function_Reference/add_meta_box#Parameters
* @link https://github.com/WebDevStudios/Taxonomy_Single_Term/blob/master/README.md
* @version 0.2.4
*/
class Taxonomy_Single_Term {
/**
* For version/feature-checking.
* @since 0.2.4
*/
const VERSION = '0.2.4';
/**
* Post types where metabox should be replaced (defaults to all post_types associated with taxonomy)
* @since 0.1.0
* @var array
*/
protected $post_types = array();
/**
* Taxonomy slug
* @since 0.1.0
* @var string
*/
protected $slug = '';
/**
* Taxonomy object
* @since 0.1.0
* @var object
*/
protected $taxonomy = false;
/**
* Taxonomy_Single_Term_Walker object
* @since 0.1.0
* @var object
*/
protected $walker = false;
/**
* New metabox title. Defaults to Taxonomy name
* @since 0.1.0
* @var string
*/
protected $metabox_title = '';
/**
* Metabox priority. (vertical placement)
* 'high', 'core', 'default' or 'low'
* @since 0.1.0
* @var string
*/
protected $priority = 'high';
/**
* Metabox position. (column placement)
* 'normal', 'advanced', or 'side'
* @since 0.1.0
* @var string
*/
protected $context = 'side';
/**
* Set to true to hide "None" option & force a term selection
* @since 0.1.1
* @var boolean
*/
protected $force_selection = false;
/**
* Whether hierarchical taxonomy inputs should be indented to represent hierarchy
* @since 0.1.2
* @var boolean
*/
protected $indented = true;
/**
* Checks if there is a bulk-edit term to set
* @var boolean|term object
*/
protected $to_set = false;
/**
* Array of post ids whose terms have been reset from bulk-edit. (prevents recursion)
* @var array
*/
protected $single_term_set = array();
/**
* What input element to use in the taxonomy meta box (radio or select)
* @var array
*/
protected $input_element = 'radio';
/**
* Whether adding new terms via the metabox is permitted
* @since 0.2.0
* @var boolean
*/
protected $allow_new_terms = false;
/**
* Default for the selector
* @since 0.2.2
* @var array
*/
protected $default = array();
/**
* Initiates our metabox action
* @since 0.1.0
* @param string $tax_slug Taxonomy slug
* @param array $post_types post-types to display custom metabox
* @param string $type display type radio or select
* @param array $default default for the taxonomy
*/
public function __construct( $tax_slug, $post_types = array(), $type = 'radio', $default = array() ) {
$this->slug = $tax_slug;
$this->post_types = is_array( $post_types ) ? $post_types : array( $post_types );
$this->input_element = in_array( (string) $type, array( 'radio', 'select' ) ) ? $type : $this->input_element;
$this->default = $this->process_default( $default );
add_action( 'add_meta_boxes', array( $this, 'add_input_element' ) );
add_action( 'admin_footer', array( $this, 'js_checkbox_transform' ) );
add_action( 'wp_ajax_taxonomy_single_term_add', array( $this, 'ajax_add_term' ) );
// Handle bulk-editing
if ( isset( $_REQUEST['bulk_edit'] ) && __( 'Update' ) == $_REQUEST['bulk_edit'] ) {
$this->bulk_edit_handler();
}
}
/**
* Process default value for settings
*
* @param array $default
*
* @return array
*/
protected function process_default( $default = array() ) {
$default = (array) $default;
if ( empty( $default ) ) {
$default = array( (int) get_option( 'default_' . $this->slug ) );
}
foreach ( $default as $index => $default_item ) {
if ( is_numeric( $default_item ) ) {
continue;
}
$term = get_term_by( 'slug', $default_item, $this->slug );
if ( $term === false ) {
$term = get_term_by( 'name', $default_item, $this->slug );
}
$default[ $index ] = ( $term instanceof WP_Term ) ? $term->term_id : false;
}
return array_filter( $default );
}
/**
* Removes and replaces the built-in taxonomy metabox with our own.
* @since 0.1.0
*/
public function add_input_element() {
// test the taxonomy slug construtor is an actual taxonomy
if ( ! $this->taxonomy() ) {
return;
}
foreach ( $this->post_types() as $key => $cpt ) {
// remove default category type metabox
remove_meta_box( $this->slug . 'div', $cpt, 'side' );
// remove default tag type metabox
remove_meta_box( 'tagsdiv-' . $this->slug, $cpt, 'side' );
// add our custom radio box
add_meta_box( $this->slug . '_input_element', $this->metabox_title(), array( $this, 'input_element' ), $cpt, $this->context, $this->priority );
}
}
/**
* Displays our taxonomy input metabox
* @since 0.1.0
* @todo Abstract inline javascript to it's own file and localize it
*/
public function input_element() {
do_action( 'taxonomy_single_term_metabox_top', $this );
// uses same noncename as default box so no save_post hook needed
wp_nonce_field( 'taxonomy_'. $this->slug, 'taxonomy_noncename' );
$class = $this->indented ? 'taxonomydiv' : 'not-indented';
$class .= 'category' !== $this->slug ? ' ' . $this->slug . 'div' : '';
$class .= ' tabs-panel';
$this->namefield = 'category' == $this->slug ? 'post_category' : 'tax_input[' . $this->slug . ']';
$this->namefield = $this->taxonomy()->hierarchical ? $this->namefield . '[]' : $this->namefield;
$el_open_cb = $this->input_element . '_open';
$el_close_cb = $this->input_element . '_close';
?>
<div id="taxonomy-<?php echo $this->slug; ?>" class="<?php echo $class; ?>">
<?php $this->{$el_open_cb}() ?>
<?php $this->term_fields_list(); ?>
<?php $this->{$el_close_cb}() ?>
<?php if ( $this->allow_new_terms ) {
$this->terms_adder_button();
} ?>
<div style="clear:both;"></div>
</div>
<?php
do_action( 'taxonomy_single_term_metabox_bottom', $this );
}
/**
* Select wrapper open
* @since 0.2.0
*/
public function select_open() {
?>
<select style="display:block;width:100%;margin-top:12px;" name="<?php echo $this->namefield; ?>" id="<?php echo $this->slug; ?>checklist" class="form-no-clear">
<?php if ( ! $this->force_selection ) : ?>
<option value="0"><?php echo esc_html( apply_filters( 'taxonomy_single_term_select_none', __( 'None' ) ) ); ?></option>
<?php endif;
}
/**
* Radio wrapper open
* @since 0.2.0
*/
public function radio_open() {
?>
<ul id="<?php echo $this->slug; ?>checklist" data-wp-lists="list:<?php echo $this->slug; ?>" class="categorychecklist form-no-clear">
<?php if ( ! $this->force_selection ) : ?>
<li style="display:none;">
<input id="taxonomy-<?php echo $this->slug; ?>-clear" type="radio" name="<?php echo $this->namefield; ?>" value="0" />
</li>
<?php endif;
}
/**
* Select wrapper close
* @since 0.2.0
*/
public function select_close() {
?>
</select>
<?php
}
/**
* Radio wrapper close
* @since 0.2.0
*/
public function radio_close() {
?>
</ul>
<p style="margin-bottom:0;float:left;width:50%;">
<a class="button" id="taxonomy-<?php echo $this->slug; ?>-trigger-clear" href="#"><?php _e( 'Clear' ); ?></a>
</p>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#taxonomy-<?php echo $this->slug; ?>-trigger-clear').click(function(){
$('#taxonomy-<?php echo $this->slug; ?> input:checked').prop( 'checked', false );
$('#taxonomy-<?php echo $this->slug; ?>-clear').prop( 'checked', true );
return false;
});
});
</script>
<?php
}
/**
* wp_terms_checklist wrapper which outputs the terms list
* @since 0.2.0
*/
public function term_fields_list( $post_id = null, $args = array() ) {
$post_id = $post_id ? $post_id : get_the_ID();
$selected = wp_get_post_terms( $post_id, $this->slug );
$selected = is_wp_error( $selected ) || empty( $selected )
? $this->default
: array_shift( $selected );
if ( isset( $selected->term_id ) ) {
$selected = $selected->term_id;
}
$args = wp_parse_args( $args, array(
'taxonomy' => $this->slug,
'selected_cats' => $selected,
'popular_cats' => false,
'checked_ontop' => false,
'walker' => $this->walker(),
) );
$result = wp_terms_checklist( $post_id, $args );
if ( isset( $args['echo'] ) && ! $args['echo'] ) {
return $result;
}
}
/**
* Adds button (and associated JS) for adding new terms
* @since 0.2.0
*/
public function terms_adder_button() {
?>
<p style="margin-bottom:0;float:right;width:50%;text-align:right;">
<a class="button-secondary" id="taxonomy-<?php echo $this->slug; ?>-new" href="#"<?php if ( 'radio' == $this->input_element ) : ?> style="display:inline-block;margin-top:0.4em;"<?php endif; ?>><?php _e( 'Add New' ); ?></a>
</p>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#taxonomy-<?php echo $this->slug; ?>-new').click(function(e){
e.preventDefault();
var termName = prompt( "Add New <?php echo esc_attr( $this->taxonomy()->labels->singular_name ); ?>", "New <?php echo esc_attr( $this->taxonomy()->labels->singular_name ); ?>" );
if( ! termName ) {
return;
}
if(termName != null) {
var data = {
'action' : 'taxonomy_single_term_add',
'term_name' : termName,
'taxonomy' : '<?php echo $this->slug; ?>',
'nonce' : '<?php echo wp_create_nonce( 'taxonomy_'. $this->slug, '_add_term' ); ?>'
};
$.post( ajaxurl, data, function(response) {
window.console.log( 'response', response );
if( response.success ){
<?php if ( 'radio' == $this->input_element ) : ?>
$('#taxonomy-<?php echo $this->slug; ?> input:checked').prop( 'checked', false );
<?php else : ?>
$('#taxonomy-<?php echo $this->slug; ?> option').prop( 'selected', false );
<?php endif; ?>
$('#<?php echo $this->slug; ?>checklist').append( response.data );
} else {
window.alert( '<?php printf( __( 'There was a problem adding a new %s' ), esc_attr( $this->taxonomy()->labels->singular_name ) ); ?>: ' + "\n" + response.data );
}
});
}
});
});
</script>
<?php
}
/**
* AJAX callback to add terms inline
* @since 0.2.0
*/
function ajax_add_term() {
$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : '';
$term_name = isset( $_POST['term_name'] ) ? sanitize_text_field( $_POST['term_name'] ) : false;
$taxonomy = isset( $_POST['taxonomy'] ) ? sanitize_text_field( $_POST['taxonomy'] ) : false;
$friendly_taxonomy = $this->taxonomy()->labels->singular_name;
// Ensure user is allowed to add new terms
if( !$this->allow_new_terms ) {
wp_send_json_error( __( "New $friendly_taxonomy terms are not allowed" ) );
}
if( !taxonomy_exists( $taxonomy ) ) {
wp_send_json_error( __( "Taxonomy $friendly_taxonomy does not exist. Cannot add term" ) );
}
if( !wp_verify_nonce( $nonce, 'taxonomy_' . $taxonomy, '_add_term' ) ) {
wp_send_json_error( __( "Cheatin' Huh? Could not verify security token" ) );
}
if( term_exists( $term_name, $taxonomy ) ) {
wp_send_json_error( __( "The term '$term_name' already exists in $friendly_taxonomy" ) );
}
$result = wp_insert_term( $term_name, $taxonomy );
if ( is_wp_error( $result ) ) {
wp_send_json_error( $result->get_error_message() );
}
$term = get_term_by( 'id', $result['term_id'], $taxonomy );
if ( ! isset( $term->term_id ) ) {
wp_send_json_error();
}
$field_name = $taxonomy == 'category'
? 'post_category'
: 'tax_input[' . $taxonomy . ']';
$field_name = $this->taxonomy()->hierarchical
? $field_name . '[]'
: $field_name;
$args = array(
'id' => $taxonomy . '-' . $term->term_id,
'name' => $field_name,
'value' => $this->taxonomy()->hierarchical ? $term->term_id : $term->slug,
'checked' => ' checked="checked"',
'selected' => ' selected="selected"',
'disabled' => '',
'label' => esc_html( apply_filters( 'the_category', $term->name ) ),
);
$output = '';
$output .= 'radio' == $this->input_element
? $this->walker()->start_el_radio( $args )
: $this->walker()->start_el_select( $args );
// $output is handled by reference
$this->walker()->end_el( $output, $term );
wp_send_json_success( $output );
}
/**
* Add some JS to the post listing page to transform the quickedit inputs
* @since 0.1.3
*/
public function js_checkbox_transform() {
$screen = get_current_screen();
$taxonomy = $this->taxonomy();
if (
empty( $taxonomy ) || empty( $screen )
|| ! isset( $taxonomy->object_type )
|| ! isset( $screen->post_type )
|| ! in_array( $screen->post_type, $taxonomy->object_type )
)
return;
?>
<script type="text/javascript">
// Handles changing input types to radios for WDS_Taxonomy_Radio
jQuery(document).ready(function($){
var $postsFilter = $('#posts-filter');
var $theList = $postsFilter.find('#the-list');
// Handles changing the input type attributes
var changeToRadio = function( $context ) {
$context = $context ? $context : $theList;
var $taxListInputs = $context.find( '.<?php echo $this->slug; ?>-checklist li input' );
if ( $taxListInputs.length ) {
// loop and switch input types
$taxListInputs.each( function() {
$(this).attr( 'type', 'radio' ).addClass('transformed-to-radio');
});
}
};
$postsFilter
// Handle converting radios in bulk-edit row
.on( 'click', '#doaction, #doaction2', function(){
var name = $(this).attr('id').substr(2);
if ( 'edit' === $( 'select[name="' + name + '"]' ).val() ) {
setTimeout( function() {
changeToRadio( $theList.find('#bulk-edit') );
}, 50 );
}
})
// when clicking new radio inputs, be sure to uncheck all but the one clicked
.on( 'change', '.transformed-to-radio', function() {
var $this = $(this);
$siblings = $this.parents( '.<?php echo $this->slug; ?>-checklist' ).find( 'li .transformed-to-radio' ).prop( 'checked', false );
$this.prop( 'checked', true );
});
// Handle converting radios in inline-edit rows
$theList.find('.editinline').on( 'click', function() {
var $this = $(this);
setTimeout( function() {
var $editRow = $this.parents( 'tr' ).next().next();
changeToRadio( $editRow );
}, 50 );
});
});
</script>
<?php
}
/**
* Handles checking if object terms need to be set when bulk-editing posts
* @since 0.2.1
*/
public function bulk_edit_handler() {
// Get wp tax name designation
$name = $this->slug;
if ( 'category' == $name ) {
$name = 'post_category';
}
if ( 'tag' == $name ) {
$name = 'post_tag';
}
// If this tax name exists in the query arg
if ( isset( $_REQUEST[ $name ] ) && is_array( $_REQUEST[ $name ] ) ) {
$this->to_set = end( $_REQUEST[ $name ] );
} elseif ( isset( $_REQUEST['tax_input'][ $name ] ) && is_array( $_REQUEST['tax_input'][ $name ] ) ) {
$this->to_set = end( $_REQUEST['tax_input'][ $name ] );
}
// Then get it's term object
if ( $this->to_set ) {
$this->to_set = get_term( $this->to_set, $this->slug );
// And hook in our re-save action
add_action( 'set_object_terms', array( $this, 'maybe_resave_terms' ), 10, 5 );
}
}
/**
* Handles resaving terms to post when bulk-editing so that only one term will be applied
* @since 0.1.4
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
*/
public function maybe_resave_terms( $object_id, $terms, $tt_ids, $taxonomy, $append ) {
if (
// if the terms being edited are not this taxonomy
$taxonomy != $this->slug
// or we already did our magic
|| in_array( $object_id, $this->single_term_set, true )
) {
// Then bail
return;
}
// Prevent recursion
$this->single_term_set[] = $object_id;
// Replace terms with the one term
wp_set_object_terms( $object_id, $this->to_set->slug, $taxonomy, $append );
}
/**
* Gets the taxonomy object from the slug
* @since 0.1.0
* @return object Taxonomy object
*/
public function taxonomy() {
$this->taxonomy = $this->taxonomy ? $this->taxonomy : get_taxonomy( $this->slug );
return $this->taxonomy;
}
/**
* Gets the taxonomy's associated post_types
* @since 0.1.0
* @return array Taxonomy's associated post_types
*/
public function post_types() {
$this->post_types = !empty( $this->post_types ) ? $this->post_types : $this->taxonomy()->object_type;
return $this->post_types;
}
/**
* Gets the metabox title from the taxonomy object's labels (or uses the passed in title)
* @since 0.1.0
* @return string Metabox title
*/
public function metabox_title() {
$this->metabox_title = !empty( $this->metabox_title ) ? $this->metabox_title : $this->taxonomy()->labels->name;
return $this->metabox_title;
}
/**
* Gets the Taxonomy_Single_Term_Walker object for use in term_fields_list and ajax_add_term
* @since 0.2.0
* @return object Taxonomy_Single_Term_Walker object
*/
public function walker() {
if ( $this->walker ) {
return $this->walker;
}
require_once( 'walker.taxonomy-single-term.php' );
$this->walker = new Taxonomy_Single_Term_Walker( $this->taxonomy()->hierarchical, $this->input_element );
return $this->walker;
}
/**
* Set the object properties.
*
* @since 0.2.1
*
* @param string $property Property in object. Must be set in object.
* @param mixed $value Value of property.
*
* @return Taxonomy_Single_Term Returns Taxonomy_Single_Term object, allows for chaining.
*/
public function set( $property, $value ) {
if ( ! property_exists( $this, $property ) ) {
return $this;
}
if ( 'default' === $property ) {
$value = $this->process_default( $value );
}
$this->$property = $value;
return $this;
}
/**
* Magic getter for our object.
*
* @since 0.2.1
*
* @param string Property in object to retrieve.
* @throws Exception Throws an exception if the field is invalid.
*
* @return mixed Property requested.
*/
public function __get( $property ) {
if ( property_exists( $this, $property ) ) {
return $this->{$property};
}
throw new Exception( 'Invalid '. __CLASS__ .' property: ' . $property );
}
}
endif; // class_exists check