下面是有关如何执行此操作的完整代码。有关更多详细信息,请参见how admin ajax work 在codex上。
<?php
/* Your code to add menu on admin bar */
add_action(\'admin_bar_menu\', \'add_item\', 100);
function add_item( $admin_bar ){
global $pagenow;
$admin_bar->add_menu( array( \'id\'=>\'cache-purge\',\'title\'=>\'Cache Purge\',\'href\'=>\'#\' ) );
}
/* Here you trigger the ajax handler function using jQuery */
add_action( \'admin_footer\', \'cache_purge_action_js\' );
function cache_purge_action_js() { ?>
<script type="text/javascript" >
jQuery("li#wp-admin-bar-cache-purge .ab-item").on( "click", function() {
var data = {
\'action\': \'example_cache_purge\',
};
/* since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php */
jQuery.post(ajaxurl, data, function(response) {
alert( response );
});
});
</script> <?php
}
/* Here you hook and define ajax handler function */
add_action( \'wp_ajax_example_cache_purge\', \'example_cache_purge_callback\' );
function example_cache_purge_callback() {
global $wpdb; /* this is how you get access to the database */
/* You cache purge logic should go here. */
$response = "Cache Purged !";
echo $response;
wp_die(); /* this is required to terminate immediately and return a proper response */
}
?>