无法使‘SANITIZE_CALLBACK’用于REST参数

时间:2022-02-09 作者:gordie

我正在尝试使用sanitize_callback:

register_rest_route( SoundSystem::$rest_namespace, \'/playlist/new\', array(
  \'methods\' => WP_REST_Server::CREATABLE,
  \'callback\' => array( __class__, \'rest_add_playlist\' ),
  \'permission_callback\' => function () {
    return is_user_logged_in();
  },
  \'playlist\' => array(
    \'description\' => __( \'JSPF playlist data\', \'soundsystem\' ),
    \'type\'        => \'string\',
    \'required\' => true,
    \'sanitize_callback\' => function($value, $request, $param) {
      return \'TESTING\';
    },
  )
));
但数据似乎没有经过清理:我得到了初始值。

public static function rest_add_playlist(WP_REST_Request $request){
  $params = $request->get_params();
  $playlist = $params[\'playlist\'];//does not returns \'TESTING\'
}
我做错了什么?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

你没有得到TESTING 因为你的playlist argument 实际上应该在args 类似于so的数组:(为简洁起见,重新缩进)

register_rest_route( SoundSystem::$rest_namespace, \'/playlist/new\', array(
    \'methods\'             => WP_REST_Server::CREATABLE,
    \'callback\'            => array( __class__, \'rest_add_playlist\' ),
    \'permission_callback\' => function () {
        return is_user_logged_in();
    },
    \'args\'                => array(
        \'playlist\' => array(
            \'description\'       => __( \'JSPF playlist data\', \'soundsystem\' ),
            \'type\'              => \'string\',
            \'required\'          => true,
            \'sanitize_callback\' => function($value, $request, $param) {
                return \'TESTING\';
            },
        ),
    ), // end args
));