0

I know how to add a link in the admin bar using admin_bar_menu action. I want to run a script to purge cache on a click of button present in admin bar by AJAX.

function add_item($admin_bar){
    global $pagenow;
    $admin_bar->add_menu(array('id'=>'cache-purge','title'=>'Cache Purge','href'=>'http://example.com/purge'));
}
add_action('admin_bar_menu', 'add_item', 100);

Is there any way to run that link without going over to that but by AJAX?

1 Answer 1

5

Below is the complete code on how to do it. For more details you may like to see how admin ajax work on 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 */
} 
?>
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.