I'm trying to load the search results using Ajax. The results display correctly, but I can't seem to make get_search_query()
work in order to make the search term appear before the results. I know I could do this with Javascript, but I'm really curious as to why the WordPress functions aren't working. I've also tried using $_GET['s']
and get_query_var('s')
, neither of which works.
Please see my code below:
Functions.php
<?php add_action( 'wp_ajax_search_results', 'load_search_results' );
add_action( 'wp_ajax_nopriv_search_results', 'load_search_results' );
function load_search_results() {
$query = $_POST['query'];
$args = array(
'post_status' => array( 'publish', 'inherit' ),
's' => $query
);
$search = new WP_Query( $args );
if ( $search->have_posts() ) :
?>
<h1><?php printf( __( 'Results for: %s', 'theme' ), get_search_query() ); ?></h1>
<?php /* Start the Loop */ ?>
<?php while( $search->have_posts() ): $search->the_post();?>
<?php get_template_part( 'content', get_post_type() ); ?>
<?php endwhile;
else :?>
<p><?php _e( 'No results', 'theme' ); ?></p>
<?php endif;
die();
}?>
JS Code
$(document).on('submit', '.search-form', function( event ) {
event.preventDefault();
var $input = $(this).find('input[name="s"]');
var $sQuery = $input.val();
$('#results').html('');
$.ajax({
url: ajaxPosts.ajaxurl,
type: 'post',
data: {
action: 'search_results',
query: $sQuery
},
success: function( html ) {
$('#results').append( html );
}
});
});
$_GET['s']
will not work for two reason. Firstly you make aPOST
request and not aGET
request and secondly there is no variable with names
in your request.POST
:). Any idea as to whyget_search_query()
isn't working?get_search_query()
is not working. The flow of AJAX is different from the normal one.