如何在Wordpress自定义端点中将类方法作为回调函数调用?

Bir*_*tam 3 wordpress plugins wordpress-rest-api

我有一个自定义端点,如下所示:

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

当它不是基于类的方法时,我可以调用回调函数“ get_user_lang”。但是一旦将其转换为基于类的方法,便无法调用它。

我的课看起来像这样:

<?php
namespace T2mchat\TokenHandler;


class TokenHandler {
  function get_user_lang() {
    return "client_langs";
  }
}
?>
Run Code Online (Sandbox Code Playgroud)

我的新端点如下所示:

$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')
    ));
});
Run Code Online (Sandbox Code Playgroud)

有人对如何在WordPress Rest API自定义终结点中调用基于类的方法有任何想法吗?

Ahm*_*ruf 5

如果在类if-self中调用该钩子,并在其中定义了yout回调方法:

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

如果来自不同类别:

add_action( 'rest_api_init', function () {
    register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
        'methods' => 'GET',
        'callback' => array('className','get_user_lang')
    ));
});
Run Code Online (Sandbox Code Playgroud)

如果此解决方案不起作用,则有关问题的更多详细信息将有助于您进行定义。

  • 使用类中的钩子本身解决了我的问题,谢谢。 (2认同)