-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomment-tagger.php
1510 lines (1183 loc) · 37.5 KB
/
comment-tagger.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: Comment Tagger
* Description: Lets logged-in readers tag comments.
* Version: 0.1.4
* Author: Christian Wach
* Author URI: https://haystack.co.uk
* Plugin URI: https://github.com/christianwach/comment-tagger
* Text Domain: comment-tagger
* Domain Path: /languages
*
* @package Comment_Tagger
*/
// Define version - bumping this refreshes CSS and JS.
define( 'COMMENT_TAGGER_VERSION', '0.1.4' );
// Define Taxonomy name.
if ( ! defined( 'COMMENT_TAGGER_TAX' ) ) {
define( 'COMMENT_TAGGER_TAX', 'comment_tags' );
}
// Define Taxonomy prefix for Select2.
if ( ! defined( 'COMMENT_TAGGER_PREFIX' ) ) {
// This is a "unique-enough" prefix so we can distinguish between new tags
// and the selection of pre-existing ones when the Comment Form is posted.
define( 'COMMENT_TAGGER_PREFIX', 'cmmnt_tggr' );
}
/**
* Comment Tagger class.
*
* A class for encapsulating plugin functionality.
*
* @since 0.1
*
* @package Comment_Tagger
*/
class Comment_Tagger {
/**
* Returns a single instance of this object when called.
*
* @since 0.1
*
* @return object $instance Comment_Tagger instance.
*/
public static function instance() {
// Store the instance locally to avoid private static replication.
static $instance = null;
// Instantiate and initialise.
if ( null === $instance ) {
$instance = new Comment_Tagger();
$instance->register_hooks();
}
// Always return instance.
return $instance;
}
/**
* Actions to perform on plugin activation.
*
* @since 0.1.1
*/
public function activate() {
// Flush rules.
flush_rewrite_rules();
}
/**
* Actions to perform on plugin deactivation.
*
* For actions that are performed on plugin deletion, see 'uninstall.php'.
*
* @since 0.1.1
*/
public function deactivate() {
// Flush rules.
flush_rewrite_rules();
}
/**
* Register the hooks that our plugin needs.
*
* @since 0.1
*/
private function register_hooks() {
// Enable translation.
add_action( 'plugins_loaded', [ $this, 'enable_translation' ] );
// Create Taxonomy.
add_action( 'init', [ $this, 'create_taxonomy' ], 0 );
// Admin hooks.
// Add admin menu item.
add_action( 'admin_menu', [ $this, 'admin_page' ] );
// Hack the menu parent.
add_filter( 'parent_file', [ $this, 'parent_menu' ] );
// Add admin styles.
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_styles' ] );
// Register a meta box.
add_action( 'add_meta_boxes', [ $this, 'add_meta_box' ] );
// Intercept Comment save process.
add_action( 'comment_post', [ $this, 'intercept_comment_save' ], 20, 2 );
// Allow Comment Authors to assign Terms.
add_filter( 'map_meta_cap', [ $this, 'enable_comment_terms' ], 10, 4 );
// Intercept Edit Comment process in WordPress admin.
add_action( 'edit_comment', [ $this, 'update_comment_terms' ] );
// Intercept Edit Comment process in CommentPress front-end.
add_action( 'edit_comment', [ $this, 'edit_comment_terms' ] );
// Intercept Delete Comment process.
add_action( 'delete_comment', [ $this, 'delete_comment_terms' ] );
// Front-end hooks.
// Register any public styles.
add_action( 'wp_enqueue_scripts', [ $this, 'front_end_enqueue_styles' ], 20 );
// Register any public scripts.
add_action( 'wp_enqueue_scripts', [ $this, 'front_end_enqueue_scripts' ], 20 );
// Add tags to Comment content.
add_filter( 'get_comment_text', [ $this, 'front_end_tags' ], 10, 2 );
// Add UI to CommentPress Comments.
add_filter( 'comment_id_fields', [ $this, 'front_end_markup' ] );
// Optionally replace with CommentPress Comment hooks.
if ( defined( 'COMMENTPRESS_VERSION' ) ) {
if ( version_compare( COMMENTPRESS_VERSION, '3.9.20', '>' ) ) {
add_action( 'commentpress/core/loaded', [ $this, 'commentpress_loaded' ] );
} else {
add_action( 'commentpress_loaded', [ $this, 'commentpress_loaded' ] );
}
}
/**
* Broadcast that this plugin has loaded.
*
* @since 0.1
*/
do_action( 'comment_tagger_loaded' );
}
/**
* Customise CommentPress when it is loaded.
*
* @since 0.1
*/
public function commentpress_loaded() {
// Remove WordPress hooks.
remove_filter( 'get_comment_text', [ $this, 'front_end_tags' ], 10, 2 );
remove_filter( 'comment_id_fields', [ $this, 'front_end_markup' ] );
// Add tags to Comment content.
add_filter( 'commentpress_comment_identifier_append', [ $this, 'front_end_tags' ], 10, 2 );
// Add UI to CommentPress Comments.
add_action( 'commentpress_comment_form_pre_comment_id_fields', [ $this, 'front_end_markup_commentpress' ] );
// Add tag data to AJAX-edit Comment data.
add_filter( 'commentpress_ajax_get_comment', [ $this, 'filter_ajax_get_comment' ], 10, 1 );
// Add tag data to AJAX-edited Comment data.
add_filter( 'commentpress_ajax_edited_comment', [ $this, 'filter_ajax_edited_comment' ], 10, 1 );
}
/**
* Load translation files.
*
* A good reference on how to implement translation in WordPress:
* http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/
*
* @since 0.1
*/
public function enable_translation() {
// Load translations if they exist.
// phpcs:ignore: WordPress.WP.DeprecatedParameters.Load_plugin_textdomainParam2Found
load_plugin_textdomain(
'comment-tagger', // Unique name.
false, // Deprecated argument.
dirname( plugin_basename( __FILE__ ) ) . '/languages/' // Relative path to translation files.
);
}
/**
* Create a free-tagging Taxonomy for Comments.
*
* @since 0.1
*/
public function create_taxonomy() {
// Define Taxonomy arguments.
$args = [
// General.
'public' => true,
'hierarchical' => false,
// Labels.
'labels' => [
'name' => __( 'Comment Tags', 'comment-tagger' ),
'singular_name' => __( 'Comment Tag', 'comment-tagger' ),
'menu_name' => __( 'Comment Tags', 'comment-tagger' ),
'search_items' => __( 'Search Comment Tags', 'comment-tagger' ),
'popular_items' => __( 'Popular Comment Tags', 'comment-tagger' ),
'all_items' => __( 'All Comment Tags', 'comment-tagger' ),
'edit_item' => __( 'Edit Comment Tag', 'comment-tagger' ),
'update_item' => __( 'Update Comment Tag', 'comment-tagger' ),
'add_new_item' => __( 'Add New Comment Tag', 'comment-tagger' ),
'new_item_name' => __( 'New Comment Tag Name', 'comment-tagger' ),
'separate_items_with_commas' => __( 'Separate Comment Tags with commas', 'comment-tagger' ),
'add_or_remove_items' => __( 'Add or remove Comment Tag', 'comment-tagger' ),
'choose_from_most_used' => __( 'Choose from the most popular Comment Tags', 'comment-tagger' ),
],
// Permalinks.
'rewrite' => [
//'with_front' => true,
'slug' => apply_filters( 'comment_tagger_tax_slug', 'comments/tags' ),
],
// Capabilities.
'capabilities' => [
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'assign_' . COMMENT_TAGGER_TAX,
],
// Custom function to update the count.
'update_count_callback' => [ $this, 'update_tag_count' ],
];
register_taxonomy( COMMENT_TAGGER_TAX, 'comment', $args );
// Register any hooks/filters that rely on knowing the Taxonomy now.
add_filter( 'manage_edit-' . COMMENT_TAGGER_TAX . '_columns', [ $this, 'set_comment_column' ] );
add_action( 'manage_' . COMMENT_TAGGER_TAX . '_custom_column', [ $this, 'set_comment_column_values' ], 10, 3 );
}
/**
* Force update the number of Comments for a Taxonomy Term.
*
* @since 0.1
*/
public function refresh_tag_count() {
// Find all the Term IDs.
$terms = get_terms( COMMENT_TAGGER_TAX, [ 'hide_empty' => false ] );
$tids = [];
foreach ( $terms as $term ) {
$tids[] = $term->term_taxonomy_id;
}
// Do update.
wp_update_term_count_now( $tids, COMMENT_TAGGER_TAX );
}
/**
* Manually update the number of Comments for a Taxonomy Term.
*
* @see _update_post_term_count()
*
* @since 0.1
*
* @param array $terms List of Term Taxonomy IDs.
* @param object $taxonomy Current Taxonomy object of Terms.
*/
public function update_tag_count( $terms, $taxonomy ) {
// Access DB wrapper.
global $wpdb;
// Loop through each Term.
foreach ( (array) $terms as $term ) {
// Get count.
// phpcs:ignore: WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$count = $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->comments " .
"WHERE $wpdb->term_relationships.object_id = $wpdb->comments.comment_ID " .
"AND $wpdb->term_relationships.term_taxonomy_id = %d",
$term
) );
// Fire WordPress action.
do_action( 'edit_term_taxonomy', $term, $taxonomy );
// Update database directly.
// phpcs:ignore: WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->update( $wpdb->term_taxonomy, [ 'count' => $count ], [ 'term_taxonomy_id' => $term ] );
// Fire WordPress action.
do_action( 'edited_term_taxonomy', $term, $taxonomy );
}
}
/**
* Creates the admin menu item for the Taxonomy under the 'Comments' menu.
*
* @since 0.1
*/
public function admin_page() {
// Get Taxonomy object.
$tax = get_taxonomy( COMMENT_TAGGER_TAX );
// Add as subpage of 'Comments' menu item.
add_comments_page(
esc_attr( $tax->labels->menu_name ),
esc_attr( $tax->labels->menu_name ),
$tax->cap->manage_terms,
'edit-tags.php?taxonomy=' . $tax->name
);
}
/**
* Enqueue CSS in WP admin to tweak the appearance of various elements.
*
* @since 0.1
*/
public function enqueue_styles() {
global $pagenow;
// If we're on our Taxonomy Page.
$taxonomy_page = isset( $_GET['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_GET['taxonomy'] ) ) : '';
if ( ! empty( $taxonomy_page ) && $taxonomy_page === COMMENT_TAGGER_TAX && $pagenow == 'edit-tags.php' ) {
// Add basic stylesheet.
wp_enqueue_style(
'comment_tagger_css',
plugin_dir_url( __FILE__ ) . 'assets/css/comment-tagger-admin.css',
false,
COMMENT_TAGGER_VERSION, // Version.
'all' // Media.
);
}
// If we're on the "Edit Comment" Page.
$action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';
if ( $pagenow == 'comment.php' && ! empty( $_GET['action'] ) && $_GET['action'] === 'editcomment' ) {
// The tags meta box requires this script.
wp_enqueue_script( 'post' );
}
}
/**
* Fix a bug with highlighting the parent menu item.
*
* By default, when on the edit Taxonomy Page for a user Taxonomy, the "Posts" tab
* is highlighted. This will correct that bug.
*
* @since 0.1
*
* @param string $parent The existing parent menu item.
* @return string $parent The modified parent menu item.
*/
public function parent_menu( $parent = '' ) {
global $pagenow;
// If we're editing our Comment Taxonomy highlight the Comments menu.
if ( ! empty( $_GET['taxonomy'] ) && $_GET['taxonomy'] == COMMENT_TAGGER_TAX && $pagenow == 'edit-tags.php' ) {
$parent = 'edit-comments.php';
}
// --<
return $parent;
}
/**
* Correct the column name for Comment Taxonomies - replace "Posts" with "Comments".
*
* @since 0.1
*
* @param array $columns An array of columns to be shown in the manage Terms table.
* @return array $columns Modified array of columns to be shown in the manage Terms table.
*/
public function set_comment_column( $columns ) {
// Replace column.
unset( $columns['posts'] );
$columns['comments'] = __( 'Comments', 'comment-tagger' );
// --<
return $columns;
}
/**
* Set values for custom columns in Comment Taxonomies.
*
* @since 0.1
*
* @param string $display WP just passes an empty string here.
* @param string $column The name of the custom column.
* @param int $term_id The ID of the Term being displayed in the table.
*/
public function set_comment_column_values( $display, $column, $term_id ) {
if ( 'comments' === $column ) {
$taxonomy = isset( $_GET['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_GET['taxonomy'] ) ) : '';
if ( ! empty( $taxonomy ) ) {
$term = get_term( $term_id, $taxonomy );
echo $term->count;
}
}
}
/**
* Register a meta box for the Edit Comment screen.
*
* @since 0.1
*/
public function add_meta_box() {
// Let's use the built-in tags metabox.
add_meta_box(
'tagsdiv-post_tag',
__( 'Comment Tags', 'comment-tagger' ), // Custom name.
'comment_tagger_post_tags_meta_box', // Custom callback.
'comment',
'normal',
'default',
[ 'taxonomy' => COMMENT_TAGGER_TAX ]
);
}
/**
* Intercept the Save Comment process and maybe update Terms.
*
* @since 0.1
*
* @param int $comment_id The numeric ID of the Comment.
* @param str $comment_status The status of the Comment.
*/
public function intercept_comment_save( $comment_id, $comment_status ) {
// Bail if we didn't receive any Terms.
if ( ! isset( $_POST['comment_tagger_tags'] ) ) {
return;
}
// Bail if the Terms array is somehow invalid.
if ( ! is_array( $_POST['comment_tagger_tags'] ) ) {
return;
}
if ( count( $_POST['comment_tagger_tags'] ) === 0 ) {
return;
}
// Check and sanitise Terms array.
$comment_tagger_tags = filter_input( INPUT_POST, 'comment_tagger_tags', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( ! empty( $comment_tagger_tags ) ) {
array_walk(
$comment_tagger_tags,
function( &$item ) {
$item = sanitize_text_field( $item );
}
);
}
// Init "existing" and "new" arrays.
$existing_term_ids = [];
$new_term_ids = [];
$new_terms = [];
// Parse the received Terms.
foreach ( $comment_tagger_tags as $term ) {
// Does the Term contain our prefix?
if ( strstr( $term, COMMENT_TAGGER_PREFIX ) ) {
// It's an existing Term.
$tmp = explode( '-', $term );
// Get Term ID.
$term_id = isset( $tmp[1] ) ? intval( $tmp[1] ) : 0;
// Add to existing.
if ( $term_id !== 0 ) {
$existing_term_ids[] = $term_id;
}
} else {
// Add Term to new.
$new_terms[] = $term;
}
}
// Get sanitised Term IDs for any *new* Terms.
if ( count( $new_terms ) > 0 ) {
$new_term_ids = $this->sanitise_comment_terms( $new_terms );
}
// Combine arrays.
$term_ids = array_unique( array_merge( $existing_term_ids, $new_term_ids ) );
// Overwrite with new Terms if there are some.
if ( ! empty( $term_ids ) ) {
wp_set_object_terms( $comment_id, $term_ids, COMMENT_TAGGER_TAX, false );
}
}
/**
* Add capability to assign tags.
*
* @since 0.1.2
*
* @param array $caps The existing capabilities array for the WordPress user.
* @param str $cap The capability in question.
* @param int $user_id The numeric ID of the WordPress user.
* @param array $args The additional arguments.
* @return array $caps The modified capabilities array for the WordPress user.
*/
public function enable_comment_terms( $caps, $cap, $user_id, $args ) {
// Only apply caps to queries for edit_comment cap.
if ( 'assign_' . COMMENT_TAGGER_TAX != $cap ) {
return $caps;
}
// Always allow.
$caps = [ 'exist' ];
// --<
return $caps;
}
/**
* Save data returned by our Comment metabox in WordPress admin.
*
* @since 0.1
*
* @param int $comment_id The ID of the Comment being saved.
*/
public function update_comment_terms( $comment_id ) {
// If there's no nonce then there's no Comment meta data.
if ( ! isset( $_POST['_wpnonce'] ) ) {
return;
}
// Get our Taxonomy.
$tax = get_taxonomy( COMMENT_TAGGER_TAX );
// Make sure the user can assign Terms.
if ( ! current_user_can( $tax->cap->assign_terms ) ) {
return;
}
// Init "existing" and "new" arrays.
$existing_term_ids = [];
$new_term_ids = [];
// Get sanitised Term IDs for any *existing* Terms.
if ( isset( $_POST['tax_input'][ COMMENT_TAGGER_TAX ] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$existing_term_ids = $this->sanitise_comment_terms( wp_unslash( $_POST['tax_input'][ COMMENT_TAGGER_TAX ] ) );
}
// Get sanitised Term IDs for any *new* Terms.
if ( isset( $_POST['newtag'][ COMMENT_TAGGER_TAX ] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$new_term_ids = $this->sanitise_comment_terms( wp_unslash( $_POST['newtag'][ COMMENT_TAGGER_TAX ] ) );
}
// Combine arrays.
$term_ids = array_unique( array_merge( $existing_term_ids, $new_term_ids ) );
// Overwrite with new Terms if there are any.
if ( ! empty( $term_ids ) ) {
wp_set_object_terms( $comment_id, $term_ids, COMMENT_TAGGER_TAX, false );
clean_object_term_cache( $comment_id, COMMENT_TAGGER_TAX );
} else {
$this->delete_comment_terms( $comment_id );
}
}
/**
* Save data returned by our tags select in CommentPress front-end.
*
* @since 0.1.3
*
* @param int $comment_id The ID of the Comment being saved.
*/
public function edit_comment_terms( $comment_id ) {
// If there's no nonce then there's no Comment meta data.
if ( ! isset( $_POST['cpajax_comment_nonce'] ) ) {
return;
}
// Get our Taxonomy.
$tax = get_taxonomy( COMMENT_TAGGER_TAX );
// Make sure the user can assign Terms.
if ( ! current_user_can( $tax->cap->assign_terms ) ) {
return;
}
// Init "existing" and "new" arrays.
$existing_term_ids = [];
$new_term_ids = [];
$new_terms = [];
// Check and sanitise Terms array.
$comment_tagger_tags = filter_input( INPUT_POST, 'comment_tagger_tags', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( ! empty( $comment_tagger_tags ) ) {
array_walk(
$comment_tagger_tags,
function( &$item ) {
$item = sanitize_text_field( $item );
}
);
}
// Sanity check.
if ( ! empty( $comment_tagger_tags ) && is_array( $comment_tagger_tags ) ) {
// Parse the received Terms.
foreach ( $comment_tagger_tags as $term ) {
// Does the Term contain our prefix?
if ( strstr( $term, COMMENT_TAGGER_PREFIX ) ) {
// It's an existing Term.
$tmp = explode( '-', $term );
// Get Term ID.
$term_id = isset( $tmp[1] ) ? intval( $tmp[1] ) : 0;
// Add to existing.
if ( $term_id !== 0 ) {
$existing_term_ids[] = $term_id;
}
} else {
// Add Term to new.
$new_terms[] = $term;
}
}
}
// Get sanitised Term IDs for any *new* Terms.
if ( count( $new_terms ) > 0 ) {
$new_term_ids = $this->sanitise_comment_terms( $new_terms );
}
// Combine arrays.
$term_ids = array_unique( array_merge( $existing_term_ids, $new_term_ids ) );
// Overwrite with new Terms if there are any.
if ( ! empty( $term_ids ) ) {
wp_set_object_terms( $comment_id, $term_ids, COMMENT_TAGGER_TAX, false );
clean_object_term_cache( $comment_id, COMMENT_TAGGER_TAX );
} else {
$this->delete_comment_terms( $comment_id );
}
}
/**
* Sanitise Comment Terms.
*
* @since 0.1
*
* @param mixed $raw_terms The Term names as retrieved from $_POST.
* @return array $term_ids The array of numeric Term IDs.
*/
private function sanitise_comment_terms( $raw_terms ) {
// Is this a multi-term Taxonomy?
if ( is_array( $raw_terms ) ) {
// Yes, get Terms and validate.
$terms = array_map( 'esc_attr', $raw_terms );
} else {
// We should receive a comma-delimited array of Term names.
$terms = array_map( 'esc_attr', explode( ',', $raw_terms ) );
}
// Init Term IDs.
$term_ids = [];
// Loop through them.
foreach ( $terms as $term ) {
// Does the Term exist?
$exists = term_exists( $term, COMMENT_TAGGER_TAX );
// If it does.
if ( $exists !== 0 && $exists !== null ) {
/*
* Should be array e.g. array( 'term_id' => 12, 'term_taxonomy_id' => 34 )
* since we specify the Taxonomy.
*/
// Add Term ID to array.
$term_ids[] = $exists['term_id'];
} else {
/*
* Let's add the Term - but note: return value is either:
* WP_Error or array e.g. array( 'term_id' => 12, 'term_taxonomy_id' => 34 )
*/
$new_term = wp_insert_term( $term, COMMENT_TAGGER_TAX );
/*
* Add Term ID to array if there's no error.
*
* If there was an error somewhere and the Terms couldn't be set
* then we should let people know at some point.
*/
if ( ! is_wp_error( $new_term ) ) {
$term_ids[] = $new_term['term_id'];
}
}
}
// Sanity checks if we have Term IDs.
if ( ! empty( $term_ids ) ) {
$term_ids = array_map( 'intval', $term_ids );
$term_ids = array_unique( $term_ids );
}
// --<
return $term_ids;
}
/**
* Delete Comment Terms when a Comment is deleted.
*
* @since 0.1
*
* @param int $comment_id The ID of the Comment being saved.
*/
public function delete_comment_terms( $comment_id ) {
wp_delete_object_term_relationships( $comment_id, COMMENT_TAGGER_TAX );
clean_object_term_cache( $comment_id, COMMENT_TAGGER_TAX );
}
/**
* Show tags on front-end, appended to Comment text.
*
* @since 0.1
*
* @param str $text The content to prepend to the Comment identifer.
* @param object $comment The WordPress Comment object.
* @return str $text The markup showing the tags for a Comment.
*/
public function front_end_tags( $text = '', $comment = null ) {
// Sanity check.
if ( ! isset( $comment->comment_ID ) ) {
return $text;
}
// Get Terms for this Comment.
$terms = wp_get_object_terms( $comment->comment_ID, COMMENT_TAGGER_TAX );
// Did we get any?
if ( count( $terms ) > 0 ) {
// Init tag list.
$tag_list = [];
// Create markup for each.
foreach ( $terms as $term ) {
// Get URL.
$term_href = get_term_link( $term, COMMENT_TAGGER_TAX );
// Construct link.
$term_link = '<a class="comment_tagger_tag_link" href="' . $term_href . '">' . esc_html( $term->name ) . '</a>';
// Wrap and add to list.
$tag_list[] = '<span class="comment_tagger_tag">' . $term_link . '</span>';
}
// Wrap in identifying div.
$tags = '<div class="comment_tagger_tags">' .
'<p>' . __( 'Tagged: ', 'comment-tagger' ) . implode( ' ', $tag_list ) . '</p>' .
'</div>' . "\n\n";
} else {
// Add placeholder div.
$tags = '<div class="comment_tagger_tags"></div>' . "\n\n";
}
// Prepend to text.
$text = $tags . $text;
// --<
return $text;
}
/**
* Show front-end version of tags metabox.
*
* @since 0.1
*
* @param str $content The existing content.
* @return str $html The markup for the tags metabox.
*/
public function front_end_markup( $content = '' ) {
// Only our Taxonomy.
$taxonomies = [ COMMENT_TAGGER_TAX ];
// Config.
$args = [
'orderby' => 'count',
'order' => 'DESC',
'number' => 5,
];
// Get top 5 most used tags.
$tags = get_terms( $taxonomies, $args );
// Construct default options for Select2.
$most_used_tags_array = [];
foreach ( $tags as $tag ) {
$most_used_tags_array[] = '<option value="' . COMMENT_TAGGER_PREFIX . '-' . $tag->term_id . '">' .
esc_html( $tag->name ) .
'</option>';
}
$most_used_tags = implode( "\n", $most_used_tags_array );
// Use Select2 in "tag" mode.
$html = '<div class="comment_tagger_select2_container">
<h5 class="comment_tagger_select2_heading">' . __( 'Tag this comment', 'comment-tagger' ) . '</h5>
<p class="comment_tagger_select2_description">' .
__( 'Select from existing tags or add your own.', 'comment-tagger' ) .
'<br />' .
__( 'Separate new tags with a comma.', 'comment-tagger' ) .
'</p>
<select class="comment_tagger_select2" name="comment_tagger_tags[]" id="comment_tagger_tags" multiple="multiple" style="width: 100%;">
' . $most_used_tags . '
</select>
</div>';
// --<
return $content . $html;
}
/**
* Show front-end version of tags metabox in CommentPress.
*
* @since 0.1
*/
public function front_end_markup_commentpress() {
// Get content and echo.
echo $this->front_end_markup();
}
/**
* Add our front-end stylesheets.
*
* Currently using the 4.0.0 version of Select2. The incuded directory is a
* copy of the 'dist' directory.
*
* @see https://github.com/select2/select2/tags
*
* @since 0.1
*/
public function front_end_enqueue_styles() {
// Default to minified scripts.
$debug = '.min';
// Use uncompressed scripts when debugging.
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG === true ) {
$debug = '';
}
// Enqueue Select2 stylesheet.
wp_enqueue_style(
'comment_tagger_select2_css',
plugin_dir_url( __FILE__ ) . 'assets/external/select2/css/select2' . $debug . '.css',
false,
COMMENT_TAGGER_VERSION, // Version.
'all' // Media.
);
}
/**
* Add our front-end Javascripts.
*
* Currently using the 4.0.0 version of Select2. The incuded directory is a
* copy of the 'dist' directory
*
* @see https://github.com/select2/select2/tags
*
* @since 0.1
*/
public function front_end_enqueue_scripts() {
// Default to minified scripts.
$debug = '.min';
// Use uncompressed scripts when debugging.
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG === true ) {
$debug = '';
}
// Enqueue Select2.
wp_enqueue_script(
'comment_tagger_select2_js',
plugin_dir_url( __FILE__ ) . 'assets/external/select2/js/select2' . $debug . '.js',
[ 'jquery' ],
COMMENT_TAGGER_VERSION,
false
);
// Enqueue our custom Javascript.
wp_enqueue_script(
'comment_tagger_select2_custom_js',
plugin_dir_url( __FILE__ ) . 'assets/js/comment-tagger.js',
[ 'comment_tagger_select2_js' ],
COMMENT_TAGGER_VERSION,
false
);
// Localisation array.
$vars = [
'localisation' => [],
'data' => [],
];
// Localise with WordPress function.
wp_localize_script(
'comment_tagger_select2_custom_js',
'CommentTaggerSettings',