Skip to content

Instantly share code, notes, and snippets.

@alexmustin
Created February 4, 2018 21:31
Show Gist options
  • Save alexmustin/c22b698689ce6caf9a562c3b405e2732 to your computer and use it in GitHub Desktop.
Save alexmustin/c22b698689ce6caf9a562c3b405e2732 to your computer and use it in GitHub Desktop.
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();
}
@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

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

@mattneal-stafflink
Copy link

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

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

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

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

@KixKira
Copy link

KixKira commented Aug 25, 2022

Hi, I tried this way, but in the "li" it gives me an error, it is only solved by removing the line.

add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
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 );
        }
    });
}
<?php
}

add_action('wp_ajax_fetch' , 'fetch');
add_action('wp_ajax_nopriv_fetch','fetch');
function fetch() {
    $args = array(
        'post_type' => array('post'),
        '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($arg);
    relevanssi_do_query($the_query);
    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 href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>
            }
        endwhile;
        wp_reset_postdata();  
    endif;
    die();
}

Can you help me? @mesmaili151

@mesmaili151
Copy link

hi @KixKira
first please edit your comment and put your code in 'code-block'. and let me know what error u got.
because I really can't understand what your problem is.
but, what's ur custom post-type name? because I saw 'glossary' which is my custom post-type name.

@maximum-jesse
Copy link

maximum-jesse commented Aug 23, 2023

omment and

@KixKira It's because in that line, you're mixing php and html. Either change it to this:

            if(stripos("/{$search}/", $a) !== false) {  ?>
                <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>
            <?php }

or this:

            if(stripos("/{$search}/", $a) !== false) {              
                echo '<li><a href="'.esc_url( post_permalink() ).'">'.the_title().'</a></li>';
            }

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