Skip to content

Instantly share code, notes, and snippets.

@santanup789
Created March 10, 2021 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santanup789/3c3799e47105ed0775c5f58835e38788 to your computer and use it in GitHub Desktop.
Save santanup789/3c3799e47105ed0775c5f58835e38788 to your computer and use it in GitHub Desktop.
Wordpress Ajax Search post, custom post type anything.
//Place this code in functions.php
//add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
//---------------
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => 'post'
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h4>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">Search results will appear here</div>
@santanup789
Copy link
Author

santanup789 commented Jan 29, 2024

More Customised Code

<div class='post_search_wrapper'>
	<input type="text" name="keyword" id="keyword" placeholder="Search here...">
	<div id="datafetch" style='display: none;'>Search results will appear here</div>
</div>
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
	?>
	<script type="text/javascript">
		jQuery(function($){
			function fetch(){
				jQuery.ajax({
					url: '<?php echo admin_url('admin-ajax.php'); ?>',
					type: 'post',
					data: { action: 'data_fetch', keyword: jQuery('.post_search_wrapper input').val() },
					beforeSend: function() {
						$('.post_search_wrapper #datafetch').removeClass('noresult').html('');
					},
					success: function(data) {
						$('.post_search_wrapper #datafetch').removeClass('noresult').html( data );
						if($('.post_search_wrapper input').val() == '' || !$.trim(data)) {
							$('.post_search_wrapper #datafetch').html('').addClass('noPost noresult').html('<h4>No result found...</h4>');
						}
						else {
							$('.post_search_wrapper #datafetch').removeClass('noPost noresult');
						}
					}
				});
			}
			$('.post_search_wrapper input').keyup(function(){
				fetch();
				$('#datafetch').show();
			})
			$('.post_search_wrapper input').focus(function(){
				if($(this).val()) {
					$('#datafetch').show();
				}
			})
			$(document).on("click", function(event){
				var $trigger = $("#datafetch").parent();
				if($trigger !== event.target && !$trigger.has(event.target).length){
					$($trigger).find('#datafetch').hide();
				}            
			});
		});
	</script>
	<?php
}

//---------------
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( 
      array( 
        'posts_per_page' => -1, 
        's' => esc_attr( $_POST['keyword'] ), 
        'post_type' => 'post' 
      ) 
    );


    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post();

$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
            <h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h4>
        <?php
                                  }
    endwhile;
        wp_reset_postdata();  
    endif;

    die();
}

CSS

#datafetch {
	width: 100%;
	background: #fff;
	border-radius: 6px;
	box-shadow: 0 0 4px 0 #dadada;
	max-height: 395.3px;
	overflow: auto;
	position: absolute;
	z-index: 9999;
	margin-top: 10px;
	margin-top: 10px;
}
#datafetch h4 {
	font-size: 16px;
	font-weight: 600;
	margin: 0;
}
#datafetch h4:not(:first-child) {
	border-top: 1px solid #f7f7f7;
}
#datafetch h4 a {
	padding: 10px;
	display: flex;
	align-items: center;
}
#datafetch h4 a div {
	padding: 2px;
	border: 1px solid #dadada;
	border-radius: 4px;
	width: 50px;
	height: 50px;
	margin-right: 10px;
}
#datafetch h4 a div img {
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 4px;
}
#datafetch h4 a span {
	flex: 1;
	display: -webkit-box;
	overflow: hidden;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	line-height: 1;
	font-size: 14px;
}
.post_search_wrapper input {
	background-image: url("data:image/svg+xml,%3Csvg width='20' height='20' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M19.8106 18.9123L14.6469 13.831C15.9991 12.3619 16.8299 10.4189 16.8299 8.28085C16.8293 3.70717 13.0621 0 8.41464 0C3.7672 0 0 3.70717 0 8.28085C0 12.8545 3.7672 16.5617 8.41464 16.5617C10.4227 16.5617 12.2644 15.8672 13.711 14.7125L18.8948 19.8138C19.1474 20.0626 19.5575 20.0626 19.81 19.8138C19.8701 19.7551 19.9179 19.685 19.9505 19.6076C19.9831 19.5303 19.9999 19.4471 20 19.3632C20.0001 19.2792 19.9833 19.196 19.9508 19.1186C19.9183 19.0412 19.8706 18.971 19.8106 18.9123ZM8.41464 15.2876C4.4824 15.2876 1.29471 12.1506 1.29471 8.28085C1.29471 4.4111 4.4824 1.27406 8.41464 1.27406C12.3469 1.27406 15.5346 4.4111 15.5346 8.28085C15.5346 12.1506 12.3469 15.2876 8.41464 15.2876Z' fill='%23D8346D'/%3E%3C/svg%3E%0A");
	background-repeat: no-repeat;
	background-position: center right;
	border-width: 0 0 1px 0 !important;
	border-radius: 0 !important;
	padding-left: 0 !important;
	padding-right: 30px !important;
	outline: none;
}
#datafetch.noPost.noresult {
	padding: 10px;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment