Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ******************* Add custom fields to search ****************** //
- function cf_search_join( $join ) {
- global $wpdb;
- if ( $_POST['keyword'] ) {
- $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
- }
- return $join;
- }
- add_filter('posts_join', 'cf_search_join' );
- function cf_search_where( $where ) {
- global $pagenow, $wpdb;
- if ( $_POST['keyword']) {
- $where = preg_replace(
- "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
- "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
- }
- return $where;
- }
- add_filter( 'posts_where', 'cf_search_where' );
- function cf_search_distinct( $where ) {
- global $wpdb;
- if ( $_POST['keyword'] ) {
- return "DISTINCT";
- }
- return $where;
- }
- add_filter( 'posts_distinct', 'cf_search_distinct' );
- // ******************* AJAX SEARCH ****************** //
- add_action( 'wp_footer', 'ajax_fetch' );
- function ajax_fetch() {
- ?>
- <script type="text/javascript">
- function fetch(){
- jQuery.ajax({
- url: '<?php echo admin_url('admin-ajax.php'); ?>',
- type: 'post',
- data: { action: 'data_fetch', keyword: jQuery('#s').val() },
- success: function(data) {
- jQuery('#search-results').html( data );
- }
- });
- }
- </script>
- <?php
- }
- add_action('wp_ajax_data_fetch' , 'data_fetch');
- add_action('wp_ajax_nopriv_data_fetch','data_fetch');
- function data_fetch(){
- // projects loop
- $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('projects')));
- if( $the_query->have_posts() ) {
- while( $the_query->have_posts() ): $the_query->the_post();
- // add loop
- endwhile;
- wp_reset_postdata();
- }
- die();
- }
Advertisement
Add Comment
Please, Sign In to add comment