0

I'm trying to set up Autocomplete on a wordpress site using PHP script. But nothing is showing up currently in my code. I understand that general idea is to have a jQuery function that would use PHP script that would pull up MySQL data(suggest.php) in this case. Also if I were to put

<script>
  $( function() {
    $( "#tags" ).autocomplete({
        source: 'suggest.php',
        minLength:1

    });
  } );
</script>

in myScript.js under js folder, how would I access it? My full code below...

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
  $( function() {
    $( "#tags" ).autocomplete({
        source: 'suggest.php',
        minLength:1

    });
  } );
</script>

<form action="" method="post">   
Name:   <input type="text" name="tags" id="tags" value="<?php echo isset($_POST['tags']) ? $_POST['tags'] : '' ?>"/>
</form>

1 Answer 1

3

First of all, don't include the whole jquery-ui, it's totally unnecessary.

Second of all, don't place your scripts manually. That's why WordPress has enqueuing.

First you need to enqueue your script where the autocomplete will be, and it must depend on autocomplete. So in your functions.php you'd put

add_action( 'after_setup_theme', 'yourtheme_theme_setup' );

if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
    function yourtheme_theme_setup() {

        add_action( 'wp_enqueue_scripts', 'yourtheme_frontend_scripts' );

    }
}

if ( ! function_exists( 'yourtheme_frontend_scripts' ) ) {
    function yourtheme_frontend_scripts() {

        wp_enqueue_script( 'yourtheme_custom', get_template_directory_uri().'/js/custom.js', array( 'jquery-ui-autocomplete', 'jquery' ), '1.0.0', true );

        wp_localize_script( 'yourtheme_custom', 'yourtheme_autocomplete', array(
            'autocomplete' => json_encode($results_array), // Results array contains all your autocomplete words
        ) );
    }
}

How you call your .js file is up to you. I call it custom.js and put it inside /js folder in the theme.

You'll also need a $results_array, with all your autocomplete words here. I usually put them manually, or query the database if needed.

Then in your custom.js you'll put something like this:

jQuery(document).ready(function($) {
    "use strict";

    var autocomplete_terms = JSON.parse( yourtheme_autocomplete.autocomplete );


    $('#tags').autocomplete({
        source: autocomplete_terms,
        minLength: 1
    });

});

Should be working fine. A cool addition is if you have accents or latin extended terms is to add them to accent map

jQuery(document).ready(function($) {
    "use strict";

    var autocomplete_terms = JSON.parse( yourtheme_autocomplete.autocomplete );

    var accentMap = {
        "ä": "a",
        "ö": "o",
        "å": "a",
        "č": "c"
    };

    var normalize = function( term ) {
        var ret = "";
        for ( var i = 0; i < term.length; i++ ) {
            ret += accentMap[ term.charAt(i) ] || term.charAt(i);
        }
        return ret;
    };

    $('#tags').autocomplete({
        source: function( request, response ) {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( autocomplete_terms, function( value ) {
                value = value.label || value.value || value;
                return matcher.test( value ) || matcher.test( normalize( value ) );
            }) );
        }
    });

});

Hope this helps.

Sign up to request clarification or add additional context in comments.

9 Comments

So according to this solution, we would set up the functions that would utilize $results_array from MySQL query file for suggest.php in functions.php and set up custom.js? How would I enque custom.js in the php page? What would be the argument for "wp_enqueue_script( string $handle, string $src = false, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )" in this case?
I'm not sure what the contents of your suggest.php file are, but the $results_array needs to be an array. Whether you'll write that array by hand, or create query that will return results in form of an array is not important. It is important to have an array to pass to your JavaScript file. The enqueue part is given in my code. Paste it in your functions.php and you'll have custom.js enqueued (make sure that it is located as noted). I forgot to replace TEMPPATH constant with get_template_directory_uri() function. I'll fix it now
So basically I think got the basic idea and set up the autocomplete. But I am having 2 issues. One I was not able to get the source from suggest.php where json-encoded list would be echo'd. If I were to input the array manually, autocomplete list does not show up on the first take, but if I click on submit botton, then it shows up. Basically my custom.js file looks like this
Update your question with all the details, this will help us find the issue quicker.
(function( $ ) { $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C" ]; $( "#tags" ).autocomplete({ source: availableTags, minLength: 1 }); }); })( jQuery ); I would like to change availableTags to suggest.php
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.