When I released my Posts By Tag WordPress Plugin, I promised to write a post explaining how to use the built-in auto complete tags script in WordPress, and so here is how you do it. š
jQuery Plugin
WordPress has a jQuery Plugin called suggest, which will do the heavy lifting for us. To use this Plugin, you have to first enqueue the script using the wp_enqueue_script()
function
// Register hooks
add_action('admin_print_scripts', 'add_script');
/**
* Add script to admin page
*/
function add_script() {
// Build in tag auto complete script
wp_enqueue_script( 'suggest' );
}
Once the script is included, you have to just call a method called suggest on your jQuery collection and everything else will be taken care for you.
<?php
/**
* add script to admin page
*/
function add_script_config() {
?>
<script type="text/javascript" >
// Function to add auto suggest
function setSuggest(id) {
jQuery('#' + id).suggest("<?php echo get_bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=post_tag");
}
</script>
<?php
}
?>
If you want to support multiple tags, then you can use the following options.
- multiple – to enable multiple tags to be entered, pass true
- multipleSep – The separator symbol for multiple tags
so the code will be
<?php
/**
* add script to admin page
*/
function add_script_config() {
?>
<script type="text/javascript" >
// Function to add auto suggest
function setSuggest(id) {
jQuery('#' + id).suggest("<?php echo get_bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=post_tag", {multiple:true, multipleSep: ","});
}
</script>
<?php
}
?>
You can also use this script to auto complete other custom taxonomies, which were introduced in WordPress 2.8. For that you have to change the tax parameter in the url. The following are the default taxonomies that are available.
- post_tag
- link_category
- category
In addition to them you can also use your custom taxonomies.
So the complete code is
<?php
// Register hooks
add_action('admin_print_scripts', 'add_script');
add_action('admin_head', 'add_script_config');
/**
* Add script to admin page
*/
function add_script() {
// Build in tag auto complete script
wp_enqueue_script( 'suggest' );
}
/**
* add script to admin page
*/
function add_script_config() {
?>
<script type="text/javascript" >
// Function to add auto suggest
function setSuggest(id) {
jQuery('#' + id).suggest("<?php echo get_bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=post_tag", {multiple:true, multipleSep: ","});
}
</script>
<?php
}
?>
The only cavet to this method is that right now the admin-ajax.php file needs you to be logged in and therefore can only be used in admin pages. But in WordPress 2.9 even anonymous users can load admin-ajax.php file. If you need use auto tag completing in blog pages, then you may have to wait till 2.9 is released š