PluginProbe
Boxzilla – WordPress Popup Builder / 3.0
Boxzilla – WordPress Popup Builder v3.0
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.0, at src/admin/class-autocomplete.php

80 lines 2.0 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 add_hooks() {
8 add_action( 'wp_ajax_boxzilla_autocomplete', array( $this, 'ajax' ) );
9 }
10
11 /**
12 * AJAX listener for autocomplete
13 */
14 public function ajax() {
15 $q = ( isset( $_GET['q'] ) ) ? sanitize_text_field( $_GET['q'] ) : '';
16 $type = ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'page', 'post', 'category', 'post_type' ) ) ) ? $_GET['type'] : 'post';
17
18 // do nothing if supplied 'q' parameter is omitted or empty
19 // or less than 2 characters long
20 if( empty( $q ) || strlen( $q ) < 2 ) {
21 die();
22 }
23
24 switch( $type ) {
25
26 default:
27 case 'post':
28 case 'page':
29 echo $this->list_posts( $q, $type );
30 break;
31
32 case 'category':
33 echo $this->list_categories( $q );
34 break;
35
36 case 'post_type':
37 echo $this->list_post_types( $q );
38 break;
39 }
40
41 die();
42 }
43
44 /**
45 * @param string $query
46 * @param string $post_type
47 *
48 * @return string
49 */
50 protected function list_posts( $query, $post_type = 'post' ) {
51 global $wpdb;
52 $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 . '%%' );
53 $post_slugs = $wpdb->get_col( $sql );
54 return join( $post_slugs, PHP_EOL );
55 }
56
57 /**
58 * @param string $query
59 *
60 * @return string
61 */
62 protected function list_categories( $query ) {
63 $categories = get_terms( 'category', array( 'name__like' => $query, 'fields' => 'names', 'hide_empty' => false ) );
64 return join( $categories, PHP_EOL );
65 }
66
67 /**
68 * @param string $query
69 *
70 * @return string
71 */
72 protected function list_post_types( $query ) {
73 $post_types = get_post_types( array( 'public' => true ), 'names' );
74 $matched_post_types = array_filter( $post_types, function( $name ) use( $query ) {
75 return strpos( $name, $query ) === 0;
76 });
77
78 return join( $matched_post_types, PHP_EOL );
79 }
80 }