amberweinberg

AJAX & Custom Fields WordPress Search

Sep 4th, 2019
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. // ******************* Add custom fields to search ****************** //
  2.  
  3. function cf_search_join( $join ) {
  4.     global $wpdb;
  5.  
  6.     if ( $_POST['keyword'] ) {    
  7.         $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
  8.     }
  9.  
  10.     return $join;
  11. }
  12. add_filter('posts_join', 'cf_search_join' );
  13.  
  14. function cf_search_where( $where ) {
  15.     global $pagenow, $wpdb;
  16.  
  17.     if ( $_POST['keyword']) {
  18.         $where = preg_replace(
  19.             "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
  20.             "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
  21.     }
  22.  
  23.     return $where;
  24. }
  25. add_filter( 'posts_where', 'cf_search_where' );
  26.  
  27. function cf_search_distinct( $where ) {
  28.     global $wpdb;
  29.  
  30.     if ( $_POST['keyword'] ) {
  31.         return "DISTINCT";
  32.     }
  33.  
  34.     return $where;
  35. }
  36. add_filter( 'posts_distinct', 'cf_search_distinct' );
  37.    
  38. // ******************* AJAX SEARCH ****************** //
  39.    
  40. add_action( 'wp_footer', 'ajax_fetch' );
  41. function ajax_fetch() {
  42. ?>
  43. <script type="text/javascript">
  44. function fetch(){
  45.  
  46.     jQuery.ajax({
  47.         url: '<?php echo admin_url('admin-ajax.php'); ?>',
  48.         type: 'post',
  49.         data: { action: 'data_fetch', keyword: jQuery('#s').val() },
  50.         success: function(data) {
  51.             jQuery('#search-results').html( data );
  52.         }
  53.     });
  54.  
  55. }
  56. </script>
  57.  
  58. <?php
  59. }
  60.  
  61. add_action('wp_ajax_data_fetch' , 'data_fetch');
  62. add_action('wp_ajax_nopriv_data_fetch','data_fetch');
  63.  
  64. function data_fetch(){
  65.    
  66.     // projects loop
  67.  
  68.     $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('projects')));
  69.     if( $the_query->have_posts() ) {
  70.        
  71.         while( $the_query->have_posts() ): $the_query->the_post();
  72.    
  73.             // add loop    
  74.  
  75.         endwhile;
  76.         wp_reset_postdata();  
  77.     }
  78.  
  79.  
  80.     die();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment