-
Notifications
You must be signed in to change notification settings - Fork 43
WP_ajax #56
Comments
Found one way to do it: In function.php (or related file executed for each request)
Works to use a Controller method for a wp_ajax action. add_action cannot be placed into Controller constructor as it's not instanciated on ajax call. |
Thanks for the help @mtx-z. Just one question: the method must be static or could be public? |
I haven't putted it in a method. It's directly in the function.php file. I guess you could put it in a method hooked on the "init" filter maybe. EDIT: Ah you're talking about the called method from the Controller. Well I don't know if I have tested it. If you do so, please report here ! |
@mtx-z I believe it is only possible use static functions because public functions is running when the page is load (I'm using Sage starter theme). |
Tested, and it works with public methods. using
I'm able to ajax call
The action callback will itself instantiate the controller, and call the matching method from this instance (I guess). |
You can define the Here's an example: // `app/controllers/FrontPage.php`
class FrontPage extends Controller {
/**
* Constructor
*/
public function __construct() {
// handle ajax requests
add_action( 'wp_ajax_do_something', [$this, 'do_something'] );
add_action( 'wp_ajax_nopriv_do_something', [$this, 'do_something'] );
}
/**
* AJAX request callback
*
*/
public static function do_something() {
// code code beep boop
$response = "I'm heading off to the land of javascript.";
echo $response;
die();
}
} If the callback were defined as a normal NOTE: you can't call a |
Hello !
I would like to know if there's a way to use SoberWP controllers with WP_ajax ?
I tried to put the add_action into my controller __construct, but as it's an Ajax call, the constructor is never called and so the action never triggered...
Any way we could handle it ?
Thanks !
The text was updated successfully, but these errors were encountered: