Comment.php
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace ACP\Sorting\Strategy;
use ACP\CommentQueryInformation;
use ACP\Sorting\Strategy;
use WP_Comment_Query;
final class Comment extends Strategy {
/**
* @var WP_Comment_Query
*/
protected $query;
public function manage_sorting() {
add_action( 'pre_get_comments', [ $this, 'handle_sorting_request' ] );
}
private function set_comment_query( WP_Comment_Query $query ) {
$this->query = $query;
}
/**
* @return WP_Comment_Query
*/
public function get_query() {
return $this->query;
}
public function get_order() {
return $this->get_query_var( 'order' );
}
public function get_query_var( $key ) {
if ( $this->query instanceof WP_Comment_Query && isset( $this->query->query_vars[ $key ] ) ) {
return $this->query->query_vars[ $key ];
}
return null;
}
public function get_results( array $args = [] ) {
$defaults = [
'fields' => 'ids',
];
$query = new WP_Comment_Query( array_merge( $defaults, $args ) );
return $query->get_comments();
}
private function is_main_query(): bool {
return (bool) $this->get_query_var( 'orderby' );
}
/**
* @param WP_Comment_Query $query
*/
public function handle_sorting_request( WP_Comment_Query $query ) {
$this->set_comment_query( $query );
// check query conditions
if ( ! $this->is_main_query() ) {
return;
}
// run only once
remove_action( 'pre_get_comments', [ $this, __FUNCTION__ ] );
foreach ( $this->model->get_sorting_vars() as $key => $value ) {
if ( $this->is_universal_id( $key ) ) {
$key = 'comment__in';
}
$query->query_vars[ $key ] = $value;
}
// pre-sorting done with an array
$comment__in = $this->get_query_var( 'comment__in' );
if ( ! empty( $comment__in ) ) {
$query->query_vars['orderby'] = 'comment__in';
}
}
}