| 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', 'post_tag' ) ) ) ? $_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 |
case 'post_tag': |
| 41 |
echo $this->list_tags( $q ); |
| 42 |
break; |
| 43 |
} |
| 44 |
|
| 45 |
die(); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* @param string $query |
| 50 |
* @param string $post_type |
| 51 |
* |
| 52 |
* @return string |
| 53 |
*/ |
| 54 |
protected function list_posts( $query, $post_type = 'post' ) { |
| 55 |
global $wpdb; |
| 56 |
$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 . '%%' ); |
| 57 |
$post_slugs = $wpdb->get_col( $sql ); |
| 58 |
return join( $post_slugs, PHP_EOL ); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* @param string $query |
| 63 |
* |
| 64 |
* @return string |
| 65 |
*/ |
| 66 |
protected function list_categories( $query ) { |
| 67 |
$terms = get_terms( 'category', array( 'name__like' => $query, 'fields' => 'names', 'hide_empty' => false ) ); |
| 68 |
return join( $terms, PHP_EOL ); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* @param string $query |
| 73 |
* |
| 74 |
* @return string |
| 75 |
*/ |
| 76 |
protected function list_tags( $query ) { |
| 77 |
$terms = get_terms( 'post_tag', array( 'name__like' => $query, 'fields' => 'names', 'hide_empty' => false ) ); |
| 78 |
return join( $terms, PHP_EOL ); |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
/** |
| 83 |
* @param string $query |
| 84 |
* |
| 85 |
* @return string |
| 86 |
*/ |
| 87 |
protected function list_post_types( $query ) { |
| 88 |
$post_types = get_post_types( array( 'public' => true ), 'names' ); |
| 89 |
$matched_post_types = array_filter( $post_types, function( $name ) use( $query ) { |
| 90 |
return strpos( $name, $query ) === 0; |
| 91 |
}); |
| 92 |
|
| 93 |
return join( $matched_post_types, PHP_EOL ); |
| 94 |
} |
| 95 |
} |