Select2LookupService.php
2.3 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php namespace MeowCrew\RoleAndCustomerBasedPricing\Services;
use Exception;
use MeowCrew\RoleAndCustomerBasedPricing\Core\ServiceContainerTrait;
use MeowCrew\RoleAndCustomerBasedPricing\Utils\Formatter;
use WC_Customer;
use WP_Term;
use WP_User_Query;
class Select2LookupService {
use ServiceContainerTrait;
const CATEGORIES_SEARCH_ACTION = 'woocommerce_json_search_rcbp_categories';
const CUSTOMERS_SEARCH_ACTION = 'woocommerce_json_search_rcbp_customers';
public function __construct() {
add_action( 'wp_ajax_' . self::CATEGORIES_SEARCH_ACTION, array( $this, 'categoriesSearchHandler' ) );
add_action( 'wp_ajax_' . self::CUSTOMERS_SEARCH_ACTION, array( $this, 'customersSearchHandler' ) );
}
public function customersSearchHandler() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json( array() );
}
$term = isset( $_GET['term'] ) ? sanitize_text_field( $_GET['term'] ) : false;
if ( $term ) {
$wp_user_query = new WP_User_Query(
array(
'search' => '*' . $term . '*',
'search_columns' => array(
'user_login',
'user_nicename',
'user_email',
),
'fields' => 'ID',
) );
$users = $wp_user_query->get_results();
if ( $users ) {
$_users = array();
foreach ( $users as $userId ) {
try {
$customer = new WC_Customer( $userId );
} catch ( Exception $e ) {
continue;
}
if ( $customer instanceof WC_Customer ) {
$_users[ $userId ] = Formatter::formatCustomerString( $customer );
}
}
wp_send_json( $_users );
}
}
wp_send_json( array() );
}
public function categoriesSearchHandler() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json( array() );
}
$term = isset( $_GET['term'] ) ? sanitize_text_field( $_GET['term'] ) : false;
if ( $term ) {
$args = array(
'taxonomy' => array( 'product_cat' ),
'orderby' => 'id',
'order' => 'ASC',
'limit' => 5,
'hide_empty' => false,
'fields' => 'all',
'name__like' => $term
);
$terms = get_terms( $args );
if ( $terms ) {
$_terms = array();
foreach ( $terms as $term ) {
if ( $term instanceof WP_Term ) {
$_terms[ $term->term_id ] = $term->name;
}
}
wp_send_json( $_terms );
}
}
wp_send_json( array() );
}
}