Implementing Autocomplete on a Wordpress site

2019-07-26 06:54发布

So I'm working on a Wordpress site which is a directory for a variety of business types (doctors, lawyers, realtors, etc). I'd like to implement a live autosuggestion feature on one of my theme's existing searchbars. I managed to follow this tutorial (https://www.w3schools.com/php/php_ajax_livesearch.asp) and successfully implemented it.

However, this implementation of the autosuggestion immediately takes you to a dedicated link specified in an XML file. That is, when you click on the suggestion you'd like to select (ie. Dentist) it automatically takes you to that page. All I'd like the autosuggestion to do is fill the relevant text box with the selected text.

I realize that this change would probably be done through PHP, which is why I'm having trouble. I'm comfortable with HTML, CSS, and Javascript, but have little experience with PHP and would appreciate andy guidance or resources anyone could help me with.

I would also be open to any solutions to my problem that have nothing to do with the way I approached the problem.

A link to the site in question (hosted on a development domain): http://temp4.dotdevelopment.net/

The relevant search box is the box with the default text "What are you looking for?"

1条回答
Summer. ? 凉城
2楼-- · 2019-07-26 07:56

I have re-created the scripts for you. Feel free to use and modify the code.

THE SCRIPTS

Step #1: See SCRIPT #1 and SCRIPT #2 and remove both scripts from the page.

Step #2: Download this JS file and upload it to your site (e.g. to wp-content/themes/listify-child/js/).

Step #3: Load the JS file from the page (e.g. add the following before </body>):

<script src="wp-content/themes/listify-child/js/custom-auto-suggest.js"></script>

Or you can use the following PHP snippet to properly load the JS file on the page:

// Add this code snippet to functions.php
add_action( 'wp_enqueue_scripts', function() {
    // Load the JS file only on the home page.
    if ( is_home() ) {
        // Here, I assumed the JS file is at wp-content/themes/listify-child/js/custom-auto-suggest.js
        wp_enqueue_script( 'custom-auto-suggest', get_theme_file_uri( '/js/custom-auto-suggest.js' ), array( 'jquery' ), '20180302' );
    }
} );

CUSTOM CSS

Add these to the theme's stylesheet/CSS file:

/* Styles for the AJAX auto-suggest results. */

#livesearch .ac-item {
    cursor: pointer;
}

#livesearch .ac-item.active,
#livesearch .ac-item:hover {
    color: red;
}
查看更多
登录 后发表回答