Created
March 10, 2021 12:43
-
-
Save santanup789/3c3799e47105ed0775c5f58835e38788 to your computer and use it in GitHub Desktop.
Wordpress Ajax Search post, custom post type anything.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input> | |
<div id="datafetch">Search results will appear here</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More Customised Code
CSS