Implementation
Step One:
We have to add the below code to the functions.php file. It is strongly recommended to use a child theme otherwise, all your customization in functions.php will be lost after each update.
Here is the code.
/*
*Ajax search by redpishi.com
*/
add_shortcode( 'asearch', 'asearch_func' );
function asearch_func( $atts ) {
$atts = shortcode_atts( array(
'source' => 'page,post,product',
'image' => 'true'
), $atts, 'asearch' );
static $asearch_first_call = 1;
$source = $atts["source"];
$image = $atts["image"];
$sForam = '
- Please wait..
';
$java = '';
$css = '';
if ( $asearch_first_call == 1 ){
$asearch_first_call++;
return "{$sForam}{$java}{$css}"; } elseif ( $asearch_first_call > 1 ) {
$asearch_first_call++;
return "{$sForam}"; }}
add_action('wp_ajax_asearch' , 'asearch');
add_action('wp_ajax_nopriv_asearch','asearch');
function asearch(){
$the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_POST['s'] ), 'post_type' => explode(",", esc_attr( $_POST['source'] ))) );
if( $the_query->have_posts() ) :
echo '
A warm thanks to Maya for sharing the code. More details…
Step Two:
Place the Shortcode widget on a page or Popup template and add the below shortcode on the Shortcode widget box (left-side).
[asearch image="true" source="post"]
[asearch image="true" source="post"]
[asearch image="true" source="post"]
Example: Category page. You can adjust the style (CSS) as you like.
If you don’t have or are not familiar with the child theme then you may use Code Snippets or WPCode plugin for adding the code.