Skip to content

Instantly share code, notes, and snippets.

@yratof
Last active August 12, 2023 18:02
Show Gist options
  • Save yratof/a745ff451a17921a5cea to your computer and use it in GitHub Desktop.
Save yratof/a745ff451a17921a5cea to your computer and use it in GitHub Desktop.
Wordpress AJAX search through custom post type
<form role="search" method="post" class="search-form padding-4" action="<?php echo home_url( '/' ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search...', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<input class="post_type" type="hidden" name="post_type" value="frequent" />
</label>
<input type="submit" class="search-submit button brand" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>
<script type="text/javascript">
jQuery(document).ready(function($){
// Bind the submit event for your form
$('.search-form').submit(function( e ){
// Stop the form from submitting
e.preventDefault();
// Get the search term
var term = $('.search-field').val();
// Get post type
var pt = $('.post_type').val();
// Make sure the user searched for something
if ( term ){
$.get( '/', { s: term, post_type: pt }, function( data ){
// Place the fetched results inside the #content element
$('#inner-content').html( $(data).find('#inner-content') );
});
}
});
});
</script>
<?php
// Custom Search Results for FAQs
function template_chooser($template) {
global $wp_query;
$post_type = get_query_var('post_type');
if( $wp_query->is_search && $post_type == 'frequent' ) { // Change post type here <--
return locate_template('faq-search.php'); // redirect to archive-search.php
}
return $template;
}
add_filter('template_include', 'template_chooser');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment