mercredi 25 février 2015

How to make WP register page as search when query is ajaxed


I've created a search page using an archive page and a JS ajax script to pull in results from a custom wp_query(). The problem I'm facing is that WordPress doesn't register this page as a search page (is_search() returns false).


I'm guessing the is_search() checks the main query, and this doesn't register since it's a custom query?


How can I make WP register this as a search?


I've included the code I'm using. Shortened to only the relevant for brevity.


Javascript



// Get Search Form Values
function getSearchValue()
{
var searchValue = $('#rfp_search').val(); //Get search form text input value
return searchValue;
}

function run_search(paged){
var ajax_url = ajax_search_params.ajax_url;

$.ajax({
type: 'GET',
url: ajax_url,
data: {
action: 'get_search',
search: getSearchValue()
},
success: function(data)
{
$('#search-results').html(data);
},
error: function()
{
$("#search-results").html('<p>There has been an error</p>');
}
});
}


archive-rfp.php



<div id="search-results"></div>


functions.php



wp_register_script( 'ajax-search-js', get_stylesheet_directory_uri() . '/library/build/js/ajax-search.js', array( 'jquery' ), '', true );
wp_localize_script( 'ajax-search-js', 'ajax_search_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax-search-js' );

add_action ('wp_ajax_get_search', 'om_ajax_search');
add_action ('wp_ajax_nopriv_get_search', 'om_ajax_search');

function om_ajax_search(){

$query_data = $_GET;
$search_value = ($query_data['search']) ? $query_data['search'] : false;

var_dump(is_search());
var_dump($tax_query);
$args = array(
's' => $search_value,
'post_type' => 'rfp'
);
$loop = new WP_Query($args);

if( $loop->have_posts() ): ?>
<p><?php global $wp_query; echo $wp_query->found_posts.' results found.'; ?></p>
<?php
while( $loop->have_posts() ): $loop->the_post(); ?>
<h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
<?php endwhile;
else:
echo '<h2>No Posts Found<h2>';
endif;
wp_reset_postdata();
die();




Aucun commentaire:

Enregistrer un commentaire