Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress ajax function in child class

If i have this classes

class something {
    public function __construct() {
        add_action('wp_ajax_ajax_func', array( $this, 'ajax_func' ) );
    }

    public function ajax_func() {

    }  

}
class stchild extends something {

    public function __construct() {

    }

    public function ajax_func() {
        echo "Test child1";
    }  
}

How to call only ajax_func function in stchild class by ajax ?
when i try this code

jQuery.ajax({
url: 'admin-ajax.php',
data: {action : 'ajax_func'},
success: function(data){
    console.log(data);
}
});

it get all functions which called ajax_func, I want to define specific class to get this function from it. Note that there is many child classes from something class and all are activated.

like image 437
Adam Mo. Avatar asked Jun 17 '14 23:06

Adam Mo.


1 Answers

You could wrap it inside an action function.

add_action( 'wp_ajax_do_something', 'my_do_something_callback' );

function my_do_something_callback() {
    $object = new stchild;
    $object->ajax_func();
    die();
}

JS:

jQuery.ajax({
    url: ajaxurl, // Use this pre-defined variable,
                  // instead of explicitly passing 'admin-ajax.php',
    data: { action : 'do_something' },
    success: function(data){
        console.log(data);
    }
});
like image 174
Patrick Moore Avatar answered Sep 28 '22 21:09

Patrick Moore