I got a set of meta boxes on a custom post type. Two of them are simple input/text-type fields, that should have autocompleted input:
- A) Another Custom Post Type
- B) Users
Now I have the problem that I need to somehow trigger the autocomplete event. So far I have this pretty simple definition:
jQuery( document ).ready( function ($)
{
$( '#some_id' ).autocomplete(
{
minLength: 2
,source: "<?php print 'SOME_STRING'; ?>"
} );
} );
which gives me the following answer in the console, when I enter “zz”:
GET http:// localhost/wordpress/wp-admin/SOME_STRING?term=zz 404 (Not Found)
Point is that I need to run a query (as you can see above) and need to root the request for the source
option/argument from autocomplete somehow to a php callback.
I hope someone can explain me how I’d get around this. Thanks (and merry christmas in case you read this 🙂 !
Use jQuerys
getJSON
in the autocompletes source method and use WordPress’ admin-ajax.php to handle the request, to avoid having to find wp-load.php (which may have been moved) and would load WordPress on every request.First of all: get the ajax url of your WordPress blog:
This is simple:
But, we want this accessible in your javascript file, so use
wp_localize_script
Where
myajax_jsfile_handle
is the handle of your registered javascript file. Call the above when you queue your javascript file.The autocomplete source method
For your source in the JQuery UI autocomplete option…
request
is whatever is typed.These are added the url that autcomplete uses to return the suggestions.
What the above does is takes each item (the returned JSONrd rows) and gives them a label, which the autocomplete uses to display the suggestions. (In the example above the label is the content of the column ‘column’)
Tell WordPress how to do deal with the request
So the above sends to WordPress an ajax request with action ‘myajax-submit’.
When WordPress recieves this it triggers the actions
wp_ajax_myajax-submit
(if the user is logged in) orwp_ajax_nopriv_myajax-submit
if they are not. You can hook your function onto one or both of these hooks, depending on whom you intend to allow this AJAX request for. Our function will perform any necessary querys and JSON the result (the suggestions) and echo them.   Â
Disclaimer: The example returns an empty array in any case.
In your autocomplete source file (you can put a autocomplete.php file in your theme) put
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
at the top of your script. Then you can use the $wpdb to query what you want.It doesn’t use WordPress AJAX API, but it works. Hope this helps.