wp-typeahead.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /*
  3. Plugin Name: WP Typeahead
  4. Description: Add autocomplete search functionality to default WordPress search form
  5. Author: c.bavota, Michal Bluma
  6. Version: 1.0.0
  7. Author URI: http://www.bavotasan.com/
  8. */
  9. class Bavotasan_WP_Typeahead {
  10. public $plugin_url;
  11. public function __construct() {
  12. $this->plugin_url = get_template_directory_uri() . '/includes/wp-typeahead/';
  13. add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );
  14. add_action( 'wp_ajax_nopriv_ajax_search', array( $this, 'ajax_search' ) );
  15. add_action( 'wp_ajax_ajax_search', array( $this, 'ajax_search' ) );
  16. }
  17. /**
  18. * Enqueue Typeahead.js and the stylesheet
  19. *
  20. * @since 1.0.0
  21. */
  22. public function wp_enqueue_scripts() {
  23. wp_enqueue_script( 'wp_typeahead_js', $this->plugin_url . 'js/typeahead.min.js', array( 'jquery' ), '', true );
  24. wp_enqueue_script( 'wp_hogan_js' , $this->plugin_url . 'js/hogan.min.js', array( 'wp_typeahead_js' ), '', true );
  25. wp_enqueue_script( 'typeahead_wp_plugin' , $this->plugin_url . 'js/wp-typeahead.js', array( 'wp_typeahead_js', 'wp_hogan_js' ), '', true );
  26. $wp_typeahead_vars = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) );
  27. wp_localize_script( 'typeahead_wp_plugin', 'wp_typeahead', $wp_typeahead_vars );
  28. wp_enqueue_style( 'wp_typeahead_css', $this->plugin_url . 'css/typeahead.css' );
  29. }
  30. /**
  31. * Ajax query for the search
  32. *
  33. * @since 1.0.0
  34. */
  35. public function ajax_search() {
  36. if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) {
  37. $search_query = new WP_Query( array(
  38. 's' => $_REQUEST['terms'],
  39. 'posts_per_page' => 10,
  40. 'no_found_rows' => true,
  41. ) );
  42. $results = array( );
  43. if ( $search_query->get_posts() ) {
  44. foreach ( $search_query->get_posts() as $the_post ) {
  45. $title = html_entity_decode( get_the_title($the_post->ID), ENT_QUOTES, 'UTF-8' );
  46. $content = get_post_field('post_content', $the_post->ID);
  47. $post_content = wp_trim_words( $content , '38', '...' );
  48. $image_url = wp_get_attachment_url( get_post_thumbnail_id($the_post->ID) );
  49. $results[] = array(
  50. 'value' => $title,
  51. 'postContent' => $post_content,
  52. 'img_url' => $image_url,
  53. 'url' => get_permalink( $the_post->ID ),
  54. 'tokens' => explode( ' ', $title ),
  55. );
  56. }
  57. } else {
  58. $results[] = __( 'Sorry. No results match your search.', 'wp-typeahead' );
  59. }
  60. wp_reset_postdata();
  61. echo json_encode( $results );
  62. }
  63. die();
  64. }
  65. }
  66. $bavotasan_wp_typeahead = new Bavotasan_WP_Typeahead;