Wordpress: how to call a plugin function with an ajax call?

后端 未结 3 1663
一生所求
一生所求 2020-12-08 03:26

I\'m writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then

3条回答
  •  眼角桃花
    2020-12-08 04:09

    TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':

    jQuery(document).ready(function(){
        jQuery(".foobar").bind("click", function() {
            jQuery(this).toggleClass('clicked');
            jQuery.ajax({
              type:'POST',
              data:{action:'my_unique_action'},
              url: "http://mysite/wp-admin/admin-ajax.php",
              success: function(value) {
                jQuery(this).html(value);
              }
            });
        });
    });
    

    Then hook it in the plugin like this if you only want it to work for logged in users:

    add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
    

    or hook it like this to work only for non-logged in users:

    add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
    

    Use both if you want it to work for everybody.

    admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.

    EDIT

    Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:

    First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:

    jQuery(document).ready(function(){
        jQuery(".foobar").bind("click", function() {
            var val = '';
            jQuery(this).toggleClass('clicked');
            jQuery.ajax({
              type:'POST',
              data:{action:'my_unique_action'},
              url: "http://mysite/wp-admin/admin-ajax.php",
              success: function(value) {
                val = value;
              },
              complete: function(){
                jQuery(this).html(val);
              }
            });
        });
    });
    

提交回复
热议问题