I’m having an issue creating an ajax search on my single post pages. I need to limit the search results to the custom post types “fod_videos” and “post” and category 12. My issue is the search is returning all the posts under those filters and not taking the search value. I’m guessing I’m missing something obvious but I can’ figure it out. Here’s my setup.
<div class="panel">
<h2>Search Videos</h2>
<div id="my-search">
<form role="search" method="get" id="searchform" action="http://myurl.com/" >
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</form>
</div>
</div>
add_action('wp_ajax_wpa5000_search', 'wpa5000_search');
add_action('wp_ajax_nopriv_wpa5000_search', 'wpa5000_search');
function wpa5000_search(){
global $wp_query;
$search = $_POST['search_val'];
$args = array(
's' => $search,
'posts_per_page' => 10,
'cat' => 12,
'post_type' => array( 'post','fod_videos' )
);
$wp_query = new WP_Query( $args );
get_template_part( 'video-search-results' );
exit;
}
add_action( 'wp_enqueue_scripts', 'wpa56343_scripts', 100 );
function wpa56343_scripts() {
wp_enqueue_script(
'wpa56343_script',
get_template_directory_uri() . '/libs/search.js?ver=1.0',
array( 'jquery' ),
null,
false
);
wp_localize_script(
'wpa56343_script',
'WPaAjax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
// search.php
$(document).ready(function($){
$('#searchsubmit').click(function(e){
var $panel = $(this).closest(".panel");
$panel.empty();
e.preventDefault();
var search_val=$("#s").val();
$.post(
WPaAjax.ajaxurl,
{
action : 'wpa5000_search',
search_val : search_val
},
function( response ) {
$panel.append( response );
}
);
});
});
//video-search-results.php
<?php
while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
//STUFF
<?php endwhile; ?>
Instead of
'cat' => 12
and$wp_query
use'category_name' => slug
andget_posts()
.Here is a basic example how it works:
PHP
JavaScript
search.js
Restricting the search
Instead of my
$this->render_search_results( $posts );
you can also load a template from your theme and use the$posts
array in a more sophisticated result. 🙂I got the original code working, but with the custom post type (without the categories). Add a hidden input in your form with your post type like this: