How to fix characters in search autocomplete wordpress

I added a function autocomplete in my wordpress theme and its working to display the titles of posts, but I have some problems with the characters

Search results in autocomplete are like this,

Read More
Selena Gomez – Come & Get It

instead of this one
Selena Gomez – Come & Get It

My js code is here:

(function( $ ) {
    $(function() {
        var url = MyAutocomplete.url + "?action=my_search";
        $( "#s" ).autocomplete({
            source: url,
            delay: 500,
            minLength: 3
        }); 
    });

})( jQuery );

and my php function is this one

function add_scripts() {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'jquery-ui-autocomplete' );
    wp_register_style( 'jquery-ui-styles','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css' );
    wp_enqueue_style( 'jquery-ui-styles' );
    wp_register_script( 'my-autocomplete', get_template_directory_uri() . '/js/autocomplete.js', array( 'jquery', 'jquery-ui-autocomplete' ), '1.0', false );
    wp_localize_script( 'my-autocomplete', 'MyAutocomplete', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'my-autocomplete' );
}

add_action( 'wp_enqueue_scripts', 'add_scripts' );
function my_search() {
        $term = strtolower( $_GET['term'] );
        $suggestions = array();

        $loop = new WP_Query( 's=' . $term );

        while( $loop->have_posts() ) {
            $loop->the_post();
            $suggestion = array();
            $suggestion['label'] = get_the_title();
            $suggestion['link'] = get_permalink();

            $suggestions[] = $suggestion;
        }

        wp_reset_query();


        $response = json_encode( $suggestions );
        echo $response;
        exit();

}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );

where Im wrong can anyone know this issue or how to fix it?

Related posts

Leave a Reply