Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress AJAX Live Search of Post Title
<!-- // The HTML (could be part of page content) // -->
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">Search results will appear here</div>
<?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(); ?>
<h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
@val-to
Copy link

val-to commented Nov 15, 2019

Hi Alex. Isis that still a secure solution? Can i use this code now?

@alexmustin
Copy link
Author

alexmustin commented Nov 15, 2019

Hi val-to.

Yes, I am using this code for a WordPress plugin and it still works great!

@val-to
Copy link

val-to commented Nov 15, 2019

Hi val-to.

Yes, I am using this code for a WordPress plugin and it still works great!

Thank you! Great job! :-) Greetings from Switzerland.

@val-to
Copy link

val-to commented Feb 5, 2020

Hi Alex. How can I include a timeout? I would like the script to be executed after 300 milliseconds.

@val-to
Copy link

val-to commented Feb 5, 2020

Is this the right way?

// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>

<script type="text/javascript"> var search_timeout = null function fetch(){ clearTimeout(search_timeout); search_timeout = setTimeout(function(){ $.ajax({ url: '', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { $('#datafetch').html( data ); } }); }, 300); } </script>

@Vicky-Intelligaia
Copy link

Vicky-Intelligaia commented Oct 6, 2020

HI Alex,
can we have something so that it will only search for the exact keyword. Right now it list many title which are not related to our searched keyword.
Please help

@mesmaili151
Copy link

mesmaili151 commented Jun 30, 2021

HI Alex,
can we have something so that it will only search for the exact keyword. Right now it list many title which are not related to our searched keyword.
Please help

try this code:

` // 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) {?>
            <li><a class="articles-link" href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>
        <?php
                                }
    endwhile;
        wp_reset_postdata();  
    endif;
    die();
}`

@mesmaili151
Copy link

mesmaili151 commented Jun 30, 2021

but just a question! how can we search by title and also post tags?!

@mattneal-stafflink
Copy link

mattneal-stafflink commented Jul 15, 2021

I have a question: If I have a meta field (in this case, it's a suburb), how could I adjust this to:

  1. Only search a specific post type called 'property'
  2. search the meta field, which is called 'property_address_suburb'

Any help would be great :)

@EricDu
Copy link

EricDu commented Jul 31, 2021

Is there a way to modify this code to retrieve PDF media attachment pages instead of posts?
Edit: Problem solved. See fork.

@mesmaili151
Copy link

mesmaili151 commented Aug 4, 2021

I have a question: If I have a meta field (in this case, it's a suburb), how could I adjust this to:

  1. Only search a specific post type called 'property'
  2. search the meta field, which is called 'property_address_suburb'

Any help would be great :)

Hi,
for search in custom posttype, you just need to change:
'post_type' => 'post'
to
'post_type' => 'property'

and for meta fiel, please read this article:
https://developer.wordpress.org/reference/classes/wp_meta_query/

i hope it will work for you.

just another thing, test the results of search string! i had a too many problems with that and finaly i install https://wordpress.org/plugins/relevanssi/ plugin and it solved my problems.
if you install it, you have change your query a bit like that:
from:

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

to

        $args = array(
            'post_type' => array( 'post', 'glossary' ),
            'posts_per_page' => 14,
            's' => esc_attr( $_POST['keyword'] ),
            'orderby'          => 'post_date',
            'order'            => 'DESC',
            'relevanssi' => true,

        );

        $the_query = new WP_Query();
        $the_query->parse_query( $args );
        relevanssi_do_query( $the_query );
            if( $the_query->have_posts() ) :

@dominotrix
Copy link

dominotrix commented Nov 24, 2021

This works fine when I am logged in as admin. But any other user visiting the website that they arent logged-in, they cant use the search form. They get: You do not have sufficient permissions to access this page. Any idea why? @mesmaili151

@mesmaili151
Copy link

mesmaili151 commented Nov 24, 2021

did you install relevanssi plugin? and used same codes?
your visitors see this error after search in results box?

actually it works for me very well without any problem.

if its possible, send your website link to check it easier. @dominotrix

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