Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I try to implement an autocomplete search but I have some troubles to make it works correctly.

When I write in search input some words, the autocomplete search doesn't filter the results and always display all my posts. So it doesn't search at all...

And I've also some difficulties to understand the way to display custom result, like the tumbnail, the title and the category for each finded post.

Here my scripts:

require_once ($admin_path . "search_autocomplete.php");

function search_ac_init() {  
    wp_enqueue_script( 'search_ac', get_template_directory_uri() . '/js/search_ac.js', array('jquery','jquery-ui-autocomplete'),null,true); 
    wp_localize_script( 'search_ac', 'MyAcSearch', array('url' => admin_url( 'admin-ajax.php' )));
} 
add_action( 'init', 'search_ac_init' );

in search_autocomplete.php :

<?php

add_action( 'wp_ajax_search_autocomplete', 'search_autocomplete' );  
add_action( 'wp_ajax_nopriv_search_autocomplete', 'search_autocomplete' ); 

function search_autocomplete(){  
    $posts = get_posts( array(  
        'search' =>$_REQUEST['term'],  
    ) );   
    $suggestions=array();  
    global $post;  
    $args = array('post_type' => array('post', 'portfolio'), 'posts_per_page' => 10, 'post_status'  => 'publish');
    $myposts = get_posts($args);
    foreach ($myposts as $post): setup_postdata($post);  
        $suggestion = array();  
        $suggestion['label'] = esc_html($post->post_title);  
        $suggestion['link'] = get_permalink();  
        $suggestions[]= $suggestion;  
    ?>  

    //<a class="link" href="<?php echo get_permalink(); ?>");>
        //<div class="img">
            //<img class="<?php echo  wp_get_attachment_url( get_post_thumbnail_id()); ?>"/ >
        //</div>
        //<div class="title"><?php echo the_title(); ?></div>
        //<div class="post"><?php echo $post_type; ?></div>
    //</a>
    // I want to display like above
    <?php   
    endforeach;  
    $response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";  
    echo $response;    
    exit;  
}  

?>

and search_ac.js :

jQuery(document).ready(function ($){  
    var acs_action = 'search_autocomplete';  
    $("input#search").autocomplete({  
        minLength: 3,
        source: function(req, response){  
            $.getJSON(MyAcSearch.url+'?callback=?&action='+acs_action, req, response);  
        },  
        select: function(event, ui) {  
            window.location.href=ui.item.link; 
        },    
        open: function(event,ui){
            var len = $('.ui-autocomplete > li').length;
            var ImgAtocompleteWidth = 60*(1/ratio);
            $(".image-autocomplete").width(ImgAtocompleteWidth);
            $('#input-count').show();
            $('#clearInput').show();
            if (len==1) {
                $('#input-count').html(len+' result');
            } else {
                $('#input-count').html(len+' results');
                }
            },
        close: function( event, ui ){   
            $('#input-count').html('')
                             .hide();
            $('#clearInput').hide(100);
            if( $('#noMatches').is(':visible') ) {
                    $('#clearInput').show(100); 
            }       
        },
        focus: function (event, ui) {
            titleinput = ui.item.value;
            ui.item.value= $.trim(titleinput);
            $( "input#search" ).val( ui.item.value );
            $('#input-count').show();
            return false;
        },      
    }).focus(function(event, ui){
            $(this).autocomplete("search");
        })  
});  
share|improve this question
1  
possible duplicate of Ajax and autocomplete –  kaiser Jul 10 '13 at 22:37
    
Not sure because my autocomplete seems to work. But the php term seems to don't works. Whatever I type in search field it always show all my database... –  freaky Jul 10 '13 at 23:43
    
You really don't want to use $_REQUEST['term'] in a database query. At least not without escaping the input... Anyway, just go with Stephens answer. It's plain perfect. Also look at my answer over here on how to do LIKE queries with a search. –  kaiser Jul 11 '13 at 2:20
    
thank you for your help. I'm new in wordpress. I should avoid using $_REQUEST['term']? In stephens answer request is also use and also in every blog that I read on autocomplete for msyql... I try with stephens script but it's not working at all. –  freaky Jul 11 '13 at 11:41
    
Yeah, the first thing is that everyone escapes input from GET/POST/REQUEST or form fields, as it else is unsafe and you can easily hack into your database and DROP TABLE all the things. Not kool. The second thing is, that you need to update your question with your new code. Hint: Copypasta never works out -> type it char by char and try to understand what happens. Hint #2: "it's not working at all" is not a proper error description and no one wants to guess what happened, right? –  kaiser Jul 11 '13 at 12:09
show 3 more comments

1 Answer

I found my problem.

It was just a problem from my search php script! Without trim( $_REQUEST['term'] ) it will not correctly filter results.

Now like this it works perfectly:

function search_autocomplete(){ 

    $posts = get_posts( array(
            's' => trim( $_REQUEST['term'] ), 'post_type' => array('post', 'portfolio')
        ) );
    $suggestions=array();

    global $post;

    $args = array('post_type' => array('post', 'portfolio'), 'posts_per_page' => 10, 'post_status'  => 'publish');
    $post = get_posts($args);

    foreach ($posts as $post): 
        setup_postdata($post);
        $suggestion = array();
        $suggestion['label'] = esc_html($post->post_title);
        $suggestion['link'] = get_permalink();
        $suggestions[]= $suggestion;
    endforeach;

    $response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";  
    echo $response;  
    exit;
}  
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.