Last active
August 29, 2015 13:57
-
-
Save alessandrotesoro/9354361 to your computer and use it in GitHub Desktop.
Ajax Search And Autosuggest For WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery('#s').suggest(ajax.url + '?action=tdp_ajax_search_query'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add Autosuggest + Ajax Query | |
*/ | |
add_action('wp_enqueue_scripts', 'tdp_add_ajax_autosuggest'); | |
function tdp_add_ajax_autosuggest() { | |
wp_enqueue_script('suggest'); | |
$args = array( | |
'url' => admin_url('admin-ajax.php'), | |
); | |
wp_localize_script( 'suggest', 'ajax', $args ); | |
} | |
add_action('wp_ajax_tdp_ajax_search_query', 'tdp_ajax_search_query'); | |
add_action('wp_ajax_nopriv_tdp_ajax_search_query', 'tdp_ajax_search_query'); | |
function tdp_ajax_search_query() { | |
$s = trim( stripslashes( $_GET['q'] ) ); | |
$query_args = apply_filters( 'tdp_ajax_search_query_args', array( | |
's' => $s, | |
'post_status' => 'publish', | |
), $s ); | |
$query = new WP_Query( $query_args ); | |
if( $query->have_posts()) : | |
while ( $query->have_posts() ) : $query->the_post(); | |
echo get_the_title() ."\n"; | |
endwhile; | |
else : | |
echo __('Whoops looks like nothing was found...', TDP_TEXDOMAIN ); | |
endif; | |
wp_die(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment