Adding Ajax Search Box at Astra Header Search form

Ajax Search Box

You can easily add the toggle search form at Astra theme header. Theme have inbuilt option in customizer about it. Search icon is appearing at right side of the header menu. I shall add the Ajax logic in this inbuilt search form and it will fetch the search result based on search key without the page refresh. I am sharing the full steps at below:

Minimum Requirements:

  1. Astra Theme
  2. Astra Child Theme (you can use your built-in astra child theme)

Enabling The Search Icon At Header

  • Login to Dashboard
  • Navigate to Appearance -> Customize link
  • Click on Layout -> Header -> Primary Header
  • Select “Search” option from Last Item In Menu drop down list
  • Click on Publish button
  • Close the customizer now
  • Go to home page and you will see the search icon at right side of header menu

Now we shall implement the wp_ajax_ action into this existing search form.

Creating Ajax Nonce

For security purposes we need a ajax nonce. We shall add this nonce as a hidden input field into Astra search form. Without edit the core files of Astra theme, you can do it. There have a filter astra_get_search for search form HTML markup. You can easily alter the existing search form HTML with custom HTML markup.

Open the functions.php of your Astra child theme and add this PHP snippets:

Creating Ajax nonce

function wpbb_ajak_search( $search_html, $option ) {
	if( empty( $option ) )
		return $search_html;
	
	if( "search" !== astra_get_option( $option ) && "header-main-rt-section" !== $option )
		return $search_html;
	
	$nonce = wp_create_nonce( "ajax-search-nonce" );
	$nonce_input = sprintf('', $nonce );
	$search_html = str_replace( '', $nonce_input . "n", $search_html );
	
	return $search_html;
}
add_filter( 'astra_get_search', 'wpbb_ajak_search', 10, 2 );

wp_create_nonce function is creating a security nonce. I used the str_replace PHP function and added the nonce hidden input field before the HTML markup.

Performing WP_AJAX_ Action

wp_ajax_ hook is working for logged in users. Other end wp_ajax_nopriv_ hook is working for logout or guest users. In this case we shall use both hooks. In my JS script (which I shall elaborate at below) I added an action ast_ajax_search. So both hooks will be wp_ajax_ast_ajax_search and wp_ajax_nopriv_ast_ajax_search .

Again open the functions.php file of your Astra child theme and add this PHP snippets

function wpbb_do_search() {
	//* checking the nonce for security purpose
	check_ajax_referer( 'ajax-search-nonce', 'security' );
	
	//* Getting the search key and sanitizing the value for security
	$search_key = sanitize_text_field( $_POST['searchKey'] );
	
	//* Running a custom query query if there have any search key
	if( ! empty( $search_key ) ) {
		$query = new WP_Query( array(
			'post_type' => 'post', //* Only post type will filter
			'post_status' => 'publish',
			's' => $search_key,
			'suppress_filters' => TRUE,
			'posts_per_page' => '5'
		));
		
		//* Generating the popup if there have any data
		if( $query->have_posts() ) {
			while( $query->have_posts() ) {
				$query->the_post();
				echo '
' . "n"; if( has_post_thumbnail() ) { echo '
' . "n"; the_post_thumbnail( array( 70, 70 ) ); echo '
' . "n"; } echo '
' . "n"; printf('

%s

', get_permalink(), get_the_title() ); printf( '

', get_the_modified_time( get_option( 'date_format' ) ) ); echo '
' . "n"; echo '
' . "n"; } if( $query->max_num_pages > 1 ) { printf( '', get_search_link( $search_key ), __( 'View All', 'astra' ) ); } } else { echo 'Not Found'; } //* resetting the query loop wp_reset_query(); } else { echo 'Not Found'; } wp_die(); } add_action('wp_ajax_ast_ajax_search', 'wpbb_do_search'); add_action('wp_ajax_nopriv_ast_ajax_search', 'wpbb_do_search');

check_ajax_referer function is checking the security nonce. Line no 11-15  is creating the custom WP_Query args. I am fetching top 5 posts. You will edit it as per your requirements.

Line no 22-36 is creating the search results item. I am just showing the post featured image, title and post publish date. Again you will edit this code as per your requirements.

Line no 39-40 is creating a View ALL button. You can view the full search results page also.

Enqueue The JS File

Creating a JS file “ajax-search-scripts.js” and putting into js folder (case-sensitive). If js folder is not existing in your astra child theme, you will create one. JS file is getting the inputted value from the search form and performing the JQuery’s AJAX functionality. Here is the full codes of that file:

(function($){
	$(function() {		
		$(".ast-search-menu-icon .search-field").keyup(function(){
			var searchKey = $(this).val();
			var data = {
				action: 'ast_ajax_search',
				searchKey: searchKey,
				security: $('.ast-dropdown-active .ajax-search-nonce').val(),
			};

			$.post(WPBBAS.ajaxurl, data, function( response ) {
				if( response !== 'Not Found' ) {
					if( $(".search-form .search-suggestion").length > 0 ) {
						$(".search-form .search-suggestion").empty();							
						$(".search-form .search-suggestion").html( response );
						$(".search-form .search-suggestion").show();
					} else {
						var result = '
' + response + '
'; $(".ast-dropdown-active .search-form").append( result ); $(".search-form .search-suggestion").slideDown(300); } } else { remove_search_suggestion(); } }); }); $(".slide-search.astra-search-icon").on('click', function(){ $(".ast-search-menu-icon .search-field").val(''); remove_search_suggestion(); }); $(".ast-search-menu-icon .search-field").blur(function(){ remove_search_suggestion(); }); $(window).resize(function(){ if( $(".search-form .search-suggestion").length > 0 ) $(".search-form .search-suggestion").remove(); }); function remove_search_suggestion() { if( $(".search-form .search-suggestion").length > 0 ) { $(".search-form .search-suggestion").empty(); $(".search-form .search-suggestion").hide(); } } }); })(jQuery);

Open the functions.php file of Astra child theme, drop the following PHP codes and it will load the above JS file on your site.

Enqueue the JS file

function wpbb_ajax_search_script() {
	wp_enqueue_script(
		'ajax-search-script',
		get_stylesheet_directory_uri() . "/js/scripts.js",
		array(),
		filemtime( get_stylesheet_directory() . "/js/scripts.js" ),
		true
	);
	wp_localize_script('ajax-search-script', 'WPBBAS', array('ajaxurl' => admin_url('admin-ajax.php') ) );
}
add_action( 'wp_enqueue_scripts', 'wpbb_ajax_search_script' );

Adding CSS for Design

Doing final touch now. Giving the professional look of this search result div. Open the style.css file of your astra child theme and add this CSS codes.

Style

.search-suggestion {
	background: #14142b;
	-webkiy-box-shadow: 0 0 4px #000;
	-moz-box-shadow: 0 0 4px #000;
	box-shadow: 0 0 4px #000;
    border-radius: 3px;
	display: none;
	position: absolute;
	left: 0;
	top: 48px;
	width: 282px;
	z-index: 9999;
}

.search-suggestion .search-item {
	border-bottom: 1px solid #505050;
	display: inline-block;
	float: left;
	text-align: left;
	padding: 5px;
}

.search-suggestion .search-item:hover {
	background: #1a1a35;
}

.search-suggestion .search-item .alignleft {
	margin-right: 8px;
}

.search-suggestion .search-item .entry-content {
	display: inline-block;
	float: left;
	width: calc(100% - 80px);
}

.search-suggestion .search-item h2 {
	font-size: 14px;
	margin-bottom: 5px;
}

.search-suggestion .search-item h2 a {
	color: #868686;
}

.search-suggestion .search-item h2 a:hover,
.all-search-btn a {
	color: #bbb;
}

.search-suggestion .search-item .pmeta {
	font-size: 12px;
	color: #757575;
}

.all-search-btn {
	background: #131313;
    clear: both;
    display: block;
    text-align: center;
    padding: 7px 10px 11px;
}
Posted in