forked from petertoi/wp-term-order
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwp-term-order.php
743 lines (614 loc) · 19.8 KB
/
wp-term-order.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
<?php
/**
* Plugin Name: WP Term Order
* Plugin URI: https://github.com/petertoi/wp-term-order
* Author: Peter Toi
* Author URI: http://petertoi.com/
* Version: 0.2.0
* Description: Sort taxonomy terms, your way. Fork of JJJ's plugin. Does not alter the database. Uses term meta instead.
* License: GPL v2 or later
*/
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
if ( ! class_exists( 'WP_Term_Order' ) ) :
/**
* Main WP Term Order class
*
* @link https://make.wordpress.org/core/2013/07/28/potential-roadmap-for-taxonomy-meta-and-post-relationships/ Taxonomy Roadmap
*
* @since 0.1.0
*/
final class WP_Term_Order {
/**
* @var string Plugin version
*/
public $version = '0.2.0';
/**
* @var string Database version
*/
public $db_version = 201608301840;
/**
* @var string File for plugin
*/
public $file = '';
/**
* @var string URL to plugin
*/
public $url = '';
/**
* @var string Path to plugin
*/
public $path = '';
/**
* @var string Basename for plugin
*/
public $basename = '';
/**
* @var array Which taxonomies are being targeted?
*/
public $taxonomies = array();
/**
* @var boo Whether to use fancy ordering
*/
public $fancy = false;
/**
* Hook into queries, admin screens, and more!
*
* @since 0.1.0
*/
public function __construct() {
// Setup plugin
$this->file = __FILE__;
$this->url = plugin_dir_url( $this->file );
$this->path = plugin_dir_path( $this->file );
$this->basename = plugin_basename( $this->file );
$this->fancy = apply_filters( 'wp_fancy_term_order', true );
// Queries
//add_filter( 'get_terms_orderby', array( $this, 'get_terms_orderby' ), 10, 2 );
add_filter( 'terms_clauses', array( $this, 'terms_clauses' ), 10, 3 );
add_action( 'create_term', array( $this, 'add_term_order' ), 10, 3 );
add_action( 'edit_term', array( $this, 'add_term_order' ), 10, 3 );
// Get visible taxonomies
$this->taxonomies = $this->get_taxonomies();
// Always hook these in, for ajax actions
foreach ( $this->taxonomies as $value ) {
// Unfancy gets the column
if ( false === $this->fancy ) {
add_filter( "manage_edit-{$value}_columns", array( $this, 'add_column_header' ) );
add_filter( "manage_{$value}_custom_column", array( $this, 'add_column_value' ), 10, 3 );
add_filter( "manage_edit-{$value}_sortable_columns", array( $this, 'sortable_columns' ) );
}
add_action( "{$value}_add_form_fields", array( $this, 'term_order_add_form_field' ) );
add_action( "{$value}_edit_form_fields", array( $this, 'term_order_edit_form_field' ) );
}
// Ajax actions
add_action( 'wp_ajax_reordering_terms', array( $this, 'ajax_reordering_terms' ) );
// Only blog admin screens
if ( is_blog_admin() || doing_action( 'wp_ajax_inline_save_tax' ) ) {
add_action( 'admin_init', array( $this, 'admin_init' ) );
// Bail if taxonomy does not include colors
if ( ! empty( $_REQUEST['taxonomy'] ) && in_array( $_REQUEST['taxonomy'], $this->taxonomies, true ) ) {
add_action( 'load-edit-tags.php', array( $this, 'edit_tags' ) );
}
}
// Pass ths object into an action
do_action( 'wp_term_meta_order_init', $this );
}
/**
* Administration area hooks
*
* @since 0.1.0
*/
public function admin_init() {
}
/**
* Administration area hooks
*
* @since 0.1.0
*/
public function edit_tags() {
add_action( 'admin_print_scripts-edit-tags.php', array( $this, 'enqueue_scripts' ) );
add_action( 'admin_head-edit-tags.php', array( $this, 'admin_head' ) );
add_action( 'admin_head-edit-tags.php', array( $this, 'help_tabs' ) );
add_action( 'quick_edit_custom_box', array( $this, 'quick_edit_term_order' ), 10, 3 );
}
/** Assets ****************************************************************/
/**
* Enqueue quick-edit JS
*
* @since 0.1.0
*/
public function enqueue_scripts() {
wp_enqueue_script( 'term-order-quick-edit', $this->url . 'js/quick-edit.js', array( 'jquery' ), $this->db_version, true );
// Enqueue fancy ordering
if ( true === $this->fancy ) {
wp_enqueue_script( 'term-order-reorder', $this->url . 'js/reorder.js', array( 'jquery-ui-sortable' ), $this->db_version, true );
}
}
/**
* Contexutal help tabs
*
* @since 0.1.5
*/
public function help_tabs() {
// Add a helpful help tab
if ( false === $this->fancy ) {
return;
}
get_current_screen()->add_help_tab( array(
'id' => 'wp_term_order_help_tab',
'title' => __( 'Term Order', 'wp-term-order' ),
'content' => '<p>' . __( 'To reposition an item, drag and drop the row by "clicking and holding" it anywhere and moving it to its new position.', 'wp-term-order' ) . '</p>',
) );
}
/**
* Align custom `order` column
*
* @since 0.1.0
*/
public function admin_head() {
?>
<style type="text/css">
.column-order {
text-align: center;
width: 74px;
}
<?php if ( true === $this->fancy ) : ?>
.wp-list-table .ui-sortable tr:not(.no-items) {
cursor: move;
}
.striped.dragging > tbody > .ui-sortable-helper ~ tr:nth-child(even) {
background: #f9f9f9;
}
.striped.dragging > tbody > .ui-sortable-helper ~ tr:nth-child(odd) {
background: #fff;
}
.wp-list-table .to-updating tr,
.wp-list-table .ui-sortable tr.inline-editor {
cursor: default;
}
.wp-list-table .ui-sortable-placeholder {
outline: 1px dashed #bbb;
background: #f1f1f1 !important;
visibility: visible !important;
}
.wp-list-table .ui-sortable-helper {
background-color: #fff !important;
outline: 1px solid #bbb;
}
.wp-list-table .ui-sortable-helper .row-actions {
visibility: hidden;
}
.to-row-updating .check-column {
background: url('<?php echo admin_url( '/images/spinner.gif' );?>') 10px 9px no-repeat;
}
@media print,
(-o-min-device-pixel-ratio: 5/4),
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 120dpi) {
.to-row-updating .check-column {
background-image: url('<?php echo admin_url( '/images/spinner-2x.gif' );?>');
background-size: 20px 20px;
}
}
.to-row-updating .check-column input {
visibility: hidden;
}
<?php endif; ?>
</style>
<?php
}
/**
* Return the taxonomies used by this plugin
*
* @since 0.1.0
*
* @param array $args
*
* @return array
*/
private static function get_taxonomies( $args = array() ) {
// Parse arguments
$r = wp_parse_args( $args, array(
'show_ui' => true
) );
// Get & return the taxonomies
$taxonomies = get_taxonomies( $r );
// Filter taxonomies & return
return apply_filters( 'wp_term_order_get_taxonomies', $taxonomies, $r, $args );
}
/** Columns ***************************************************************/
/**
* Add the "Order" column to taxonomy terms list-tables
*
* @since 0.1.0
*
* @param array $columns
*
* @return array
*/
public function add_column_header( $columns = array() ) {
$columns['order'] = __( 'Order', 'wp-term-order' );
return $columns;
}
/**
* Output the value for the custom column, in our case: `order`
*
* @since 0.1.0
*
* @param string $empty
* @param string $custom_column
* @param int $term_id
*
* @return mixed
*/
public function add_column_value( $empty = '', $custom_column = '', $term_id = 0 ) {
// Bail if no taxonomy passed or not on the `order` column
if ( empty( $_REQUEST['taxonomy'] ) || ( 'order' !== $custom_column ) || ! empty( $empty ) ) {
return;
}
return $this->get_term_order( $term_id );
}
/**
* Allow sorting by `order` order
*
* @since 0.1.0
*
* @param array $columns
*
* @return array
*/
public function sortable_columns( $columns = array() ) {
$columns['order'] = 'order';
return $columns;
}
/**
* Add `order` to term when updating
*
* @since 0.1.0
*
* @param int $term_id The ID of the term
* @param int $tt_id Not used
* @param string $taxonomy Taxonomy of the term
*/
public function add_term_order( $term_id = 0, $tt_id = 0, $taxonomy = '' ) {
/*
* Bail if order info hasn't been POSTed, like when the "Quick Edit"
* form is used to update a term.
*/
if ( ! isset( $_POST['order'] ) ) {
return;
}
// Sanitize the value.
$order = ! empty( $_POST['order'] )
? (int) $_POST['order']
: 0;
self::set_term_order( $term_id, $taxonomy, $order );
}
/**
* Set order of a specific term
*
* @since 0.1.0
*
* @param int $term_id
* @param string $taxonomy
* @param int $order
* @param bool $clean_cache
*/
public static function set_term_order( $term_id = 0, $taxonomy = '', $order = 0, $clean_cache = false ) {
update_term_meta( $term_id, "term_order_$taxonomy", $order );
// Maybe clean the term cache
if ( true === $clean_cache ) {
clean_term_cache( $term_id, $taxonomy );
}
}
/**
* Return the order of a term
*
* @since 0.1.0
*
* @param int $term_id
*/
public function get_term_order( $term_id = 0 ) {
$order = get_term_meta( $term_id, "term_order_{$_REQUEST['taxonomy']}", true );
return ( ! empty( $order ) ) ? (int) $order : 0;
}
/** Markup ****************************************************************/
/**
* Output the "order" form field when adding a new term
*
* @since 0.1.0
*/
public static function term_order_add_form_field() {
?>
<div class="form-field form-required">
<label for="order">
<?php esc_html_e( 'Order', 'wp-term-order' ); ?>
</label>
<input type="number" pattern="[0-9.]+" name="order" id="order" value="0" size="11">
<p class="description">
<?php esc_html_e( 'Set a specific order by entering a number (1 for first, etc.) in this field.', 'wp-term-order' ); ?>
</p>
</div>
<?php
}
/**
* Output the "order" form field when editing an existing term
*
* @since 0.1.0
*
* @param object $term
*/
public function term_order_edit_form_field( $term = false ) {
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="order">
<?php esc_html_e( 'Order', 'wp-term-order' ); ?>
</label>
</th>
<td>
<input name="order" id="order" type="text" value="<?php echo $this->get_term_order( $term ); ?>" size="11"/>
<p class="description">
<?php esc_html_e( 'Terms are usually ordered alphabetically, but you can choose your own order by entering a number (1 for first, etc.) in this field.', 'wp-term-order' ); ?>
</p>
</td>
</tr>
<?php
}
/**
* Output the "order" quick-edit field
*
* @since 0.1.0
*
* @param $term
*/
public function quick_edit_term_order( $column_name = '', $screen = '', $name = '' ) {
// Bail if not the `order` column on the `edit-tags` screen for a visible taxonomy
if ( ( 'order' !== $column_name ) || ( 'edit-tags' !== $screen ) || ! in_array( $name, $this->taxonomies, true ) ) {
return false;
} ?>
<fieldset>
<div class="inline-edit-col">
<label>
<span class="title"><?php esc_html_e( 'Order', 'wp-term-order' ); ?></span>
<span class="input-text-wrap">
<input type="number" pattern="[0-9.]+" class="ptitle" name="order" value="" size="11">
</span>
</label>
</div>
</fieldset>
<?php
}
/** Query Filters *********************************************************/
/**
* Force `orderby` to `tt.order` if not explicitly set to something else
*
* @since 0.1.0
*
* @param string $orderby
*
* @return string
*/
public function get_terms_orderby( $orderby = 'name', $args = array() ) {
// Do not override if being manually controlled
if ( ! empty( $_GET['orderby'] ) && ! empty( $_GET['taxonomy'] ) ) {
return $orderby;
}
// Maybe force `orderby`
if ( empty( $args['orderby'] ) || empty( $orderby ) || ( 'order' === $args['orderby'] ) || in_array( $orderby, array( 'name', 't.name' ) ) ) {
$orderby = 'tt.order';
} elseif ( 't.name' === $orderby ) {
$orderby = 'tt.order, t.name';
}
// Return possibly modified `orderby` value
return $orderby;
}
/**
* Modify term clauses to join taxonomy_meta and set order
*
* @since 0.1.0
*
* @param array $pieces
* @param array $taxonomies
* @param array $args
*
* @return string
*/
public function terms_clauses( $pieces, $taxonomies, $args ) {
global $wpdb;
// Do not override if being manually controlled
if ( ! empty( $_GET['orderby'] ) && ! empty( $_GET['taxonomy'] ) ) {
return $pieces;
}
// Compare # of terms with term_order against # of terms without. Don't override if they don't match.
$all_terms = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_taxonomy} as tt WHERE tt.taxonomy = '{$taxonomies[0]}'" );
$ordered_terms = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_taxonomy} as tt LEFT JOIN {$wpdb->termmeta} as tm ON tt.term_id = tm.term_id WHERE tt.taxonomy = '{$taxonomies[0]}' AND tm.meta_key = 'term_order_{$taxonomies[0]}'" );
if ( $all_terms !== $ordered_terms ) {
return $pieces;
}
// Maybe force `orderby`
if ( empty( $args['orderby'] ) || ( 'order' === $args['orderby'] ) ) {
$pieces['fields'] .= ', term_meta.*';
$pieces['join'] .= "\nINNER JOIN {$wpdb->termmeta} as term_meta ON t.term_id = term_meta.term_id";
$pieces['where'] .= "\nAND term_meta.meta_key = 'term_order_{$taxonomies[0]}'";
$pieces['orderby'] = "ORDER BY term_meta.meta_value";
} elseif ( stristr( $pieces['orderby'], 't.name' ) ) {
$pieces['fields'] .= ', term_meta.*';
$pieces['join'] .= "\nINNER JOIN {$wpdb->termmeta} as term_meta ON t.term_id = term_meta.term_id";
$pieces['where'] .= "\nAND term_meta.meta_key = 'term_order_{$taxonomies[0]}'";
$pieces['orderby'] = "ORDER BY term_meta.meta_value ASC, t.name";
}
// Return possibly modified `orderby` value
return $pieces;
}
/** Admin Ajax ************************************************************/
/**
* Handle ajax term reordering
*
* This bit is inspired by the Simple Page Ordering plugin from 10up
*
* @since 0.1.0
*/
public static function ajax_reordering_terms() {
global $wpdb;
// Bail if required term data is missing
if ( empty( $_POST['id'] ) || empty( $_POST['tax'] ) || ( ! isset( $_POST['previd'] ) && ! isset( $_POST['nextid'] ) ) ) {
die( - 1 );
}
// Attempt to get the taxonomy
$tax = get_taxonomy( $_POST['tax'] );
// Bail if taxonomy does not exist
if ( empty( $tax ) ) {
die( - 1 );
}
// Bail if current user cannot assign terms
if ( ! current_user_can( $tax->cap->edit_terms ) ) {
die( - 1 );
}
// Bail if term cannot be found
$term = get_term( $_POST['id'], $_POST['tax'] );
if ( empty( $term ) ) {
die( - 1 );
}
// Sanitize positions
$taxonomy = $_POST['tax'];
$previd = empty( $_POST['previd'] ) ? false : (int) $_POST['previd'];
$nextid = empty( $_POST['nextid'] ) ? false : (int) $_POST['nextid'];
$start = empty( $_POST['start'] ) ? 1 : (int) $_POST['start'];
$excluded = empty( $_POST['excluded'] ) ?
array( $term->term_id ) :
array_filter( (array) $_POST['excluded'], 'intval' );
// Define return values
$new_pos = array();
$return_data = new stdClass;
// attempt to get the intended parent...
$parent_id = $term->parent;
$next_term_parent = $nextid
? wp_get_term_taxonomy_parent_id( $nextid, $taxonomy )
: false;
// If the preceding term is the parent of the next term, move it inside
if ( $previd === $next_term_parent ) {
$parent_id = $next_term_parent;
// If the next term's parent isn't the same as our parent, we need more info
} elseif ( $next_term_parent !== $parent_id ) {
$prev_term_parent = $previd
? wp_get_term_taxonomy_parent_id( $nextid, $taxonomy )
: false;
// If the previous term is not our parent now, set it
if ( $prev_term_parent !== $parent_id ) {
$parent_id = ( $prev_term_parent !== false )
? $prev_term_parent
: $next_term_parent;
}
}
// If the next term's parent isn't our parent, set to false
if ( $next_term_parent !== $parent_id ) {
$nextid = false;
}
$all_terms = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_taxonomy} as tt WHERE tt.taxonomy = '{$taxonomy}'" );
$ordered_terms = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_taxonomy} as tt LEFT JOIN {$wpdb->termmeta} as tm ON tt.term_id = tm.term_id WHERE tt.taxonomy = '{$taxonomy}' AND tm.meta_key = 'term_order_{$taxonomies[0]}'" );
// Get term siblings for relative ordering
$sibling_args = array(
'taxonomy' => $taxonomy,
'depth' => 1,
'number' => 100,
'parent' => $parent_id,
'hide_empty' => false,
'exclude' => $excluded,
);
if ( $all_terms === $ordered_terms ) {
$sibling_args['orderby'] = 'meta_value_num';
$sibling_args['order'] = 'ASC';
$sibling_args['meta_key'] = "term_order_{$taxonomy}";
$sibling_args['meta_query'] = array(
array(
'key' => "term_order_{$taxonomy}",
'compare' => 'EXISTS',
)
);
}
$siblings = get_terms( $sibling_args );
// Loop through siblings and update terms
foreach ( $siblings as $sibling ) {
// Skip the actual term if it's in the array
if ( $sibling->term_id === (int) $term->term_id ) {
continue;
}
// If this is the term that comes after our repositioned term, set
// our repositioned term position and increment order
if ( $nextid === (int) $sibling->term_id ) {
self::set_term_order( $term->term_id, $taxonomy, $start, true );
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
$new_pos[ $term->term_id ] = array(
'order' => $start,
'parent' => $parent_id,
'depth' => count( $ancestors ),
);
$start ++;
}
// If repositioned term has been set and new items are already in
// the right order, we can stop looping
if ( isset( $new_pos[ $term->term_id ] ) && (int) $sibling->order >= $start ) {
$return_data->next = false;
break;
}
// Set order of current sibling and increment the order
if ( $start !== (int) $sibling->order ) {
self::set_term_order( $sibling->term_id, $taxonomy, $start, true );
}
$new_pos[ $sibling->term_id ] = $start;
$start ++;
if ( empty( $nextid ) && ( $previd === (int) $sibling->term_id ) ) {
self::set_term_order( $term->term_id, $taxonomy, $start, true );
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
$new_pos[ $term->term_id ] = array(
'order' => $start,
'parent' => $parent_id,
'depth' => count( $ancestors )
);
$start ++;
}
}
// max per request
if ( ! isset( $return_data->next ) && count( $siblings ) > 1 ) {
$return_data->next = array(
'id' => $term->term_id,
'previd' => $previd,
'nextid' => $nextid,
'start' => $start,
'excluded' => array_merge( array_keys( $new_pos ), $excluded ),
'taxonomy' => $taxonomy
);
} else {
$return_data->next = false;
}
if ( empty( $return_data->next ) ) {
// If the moved term has children, refresh the page for UI reasons
$children = get_terms( $taxonomy, array(
'number' => 1,
'depth' => 1,
'orderby' => 'order',
'order' => 'ASC',
'parent' => $term->term_id,
'fields' => 'ids',
'hide_empty' => false
) );
if ( ! empty( $children ) ) {
die( 'children' );
}
}
$return_data->new_pos = $new_pos;
die( json_encode( $return_data ) );
}
}
endif;
/**
* Instantiate the main WordPress Term Order class
*
* @since 0.1.0
*/
function _wp_term_order() {
new WP_Term_Order();
}
add_action( 'init', '_wp_term_order', 99 );