Search code examples
wordpresspluginswordpress-rest-api

How to call a class method as a callback function in wordpress custom endpoint?


I have a custom endpoint which looks like this:

add_action( 'rest_api_init', function () {
    register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
        'methods' => 'GET',
        'callback' => 'get_user_lang'
    ));
});

I was able to call the callback function "get_user_lang" when it wasn't a class based method. But once I converted it to a class based method, I wasn't able to call it.

My class looks like this:

<?php
namespace T2mchat\TokenHandler;


class TokenHandler {
  function get_user_lang() {
    return "client_langs";
  }
}
?>

and my new endpoint looks like this:

$t2m = new T2mchat\TokenHandler\TokenHandler();
add_action( 'rest_api_init', function () {
    register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
        'methods' => 'GET',
        'callback' => array($t2m, 'get_user_lang')
    ));
});

Anyone have any idea on how to call a class based method in WordPress Rest API custom endpoints?


Solution

  • If the hook is called within the class if-self and yout callback method is defined there:

    add_action( 'rest_api_init', function () {
        register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
            'methods' => 'GET',
            'callback' => array($this,'get_user_lang')
        ));
    });
    

    If from different class:

    add_action( 'rest_api_init', function () {
        register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
            'methods' => 'GET',
            'callback' => array(new className,'get_user_lang')
        ));
    });
    

    If this solution is not working, a bit more details of your problem will help in defining.