PluginProbe
Boxzilla – WordPress Popup Builder / 3.4.7
Boxzilla – WordPress Popup Builder v3.4.7
3.4.11 3.4.10 3.4.9 3.4.3 3.4.4 3.4.5 3.4.6 3.4.7 3.4.8 trunk 3.0 3.0.1 3.0.2 3.0.3 3.1 3.1.1 3.1.10 3.1.11 3.1.12 3.1.13 3.1.14 3.1.15 3.1.16 3.1.17 3.1.18 All 72 releases
boxzilla / src / admin / class-autocomplete.php

class-autocomplete.php in Boxzilla – WordPress Popup Builder 3.4.7, at src/admin/class-autocomplete.php

114 lines 2.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Boxzilla\Filter;
4
5 class Autocomplete
6 {
7 public function init(): void
8 {
9 add_action('wp_ajax_boxzilla_autocomplete', [ $this, 'ajax' ], 10, 0);
10 }
11
12 /**
13 * AJAX listener for autocomplete
14 */
15 public function ajax(): void
16 {
17 $q = ( isset($_GET['q']) ) ? sanitize_text_field($_GET['q']) : '';
18 $type = ( isset($_GET['type']) && in_array($_GET['type'], [ 'page', 'post', 'category', 'post_type', 'post_tag' ], true) ) ? $_GET['type'] : 'post';
19
20 // do nothing if supplied 'q' parameter is omitted or empty
21 // or less than 2 characters long
22 if (empty($q) || strlen($q) < 2) {
23 die();
24 }
25
26 switch ($type) {
27 default:
28 case 'post':
29 case 'page':
30 echo $this->list_posts($q, $type);
31 break;
32
33 case 'category':
34 echo $this->list_categories($q);
35 break;
36
37 case 'post_type':
38 echo $this->list_post_types($q);
39 break;
40
41 case 'post_tag':
42 echo $this->list_tags($q);
43 break;
44 }
45
46 die();
47 }
48
49 /**
50 * @param string $query
51 * @param string $post_type
52 *
53 * @return string
54 */
55 protected function list_posts($query, $post_type = 'post')
56 {
57 global $wpdb;
58 $sql = $wpdb->prepare("SELECT p.post_name FROM $wpdb->posts p WHERE p.post_type = %s AND p.post_status = 'publish' AND ( p.post_title LIKE %s OR p.post_name LIKE %s ) GROUP BY p.post_name", $post_type, $query . '%%', $query . '%%');
59 $post_slugs = $wpdb->get_col($sql);
60 return join(PHP_EOL, $post_slugs);
61 }
62
63 /**
64 * @param string $query
65 *
66 * @return string
67 */
68 protected function list_categories($query)
69 {
70 $terms = get_terms([
71 'taxonomy' => 'category',
72 'name__like' => $query,
73 'fields' => 'names',
74 'hide_empty' => false,
75 ]);
76 return join(PHP_EOL, $terms);
77 }
78
79 /**
80 * @param string $query
81 *
82 * @return string
83 */
84 protected function list_tags($query)
85 {
86 $terms = get_terms([
87 'taxonomy' => 'post_tag',
88 'name__like' => $query,
89 'fields' => 'names',
90 'hide_empty' => false,
91 ]);
92 return join(PHP_EOL, $terms);
93 }
94
95
96 /**
97 * @param string $query
98 *
99 * @return string
100 */
101 protected function list_post_types($query)
102 {
103 $post_types = get_post_types([ 'public' => true ], 'names');
104 $matched_post_types = array_filter(
105 $post_types,
106 function ($name) use ($query) {
107 return strpos($name, $query) === 0;
108 }
109 );
110
111 return join(PHP_EOL, $matched_post_types);
112 }
113 }
114