programing

워드프레스 플러그인 끝점에 REST 경로를 등록할 위치

jooyons 2023. 11. 1. 22:20
반응형

워드프레스 플러그인 끝점에 REST 경로를 등록할 위치

등록 기능은 어디로 이동해야 합니까? (register_rest_route())

  • 테마/자녀 기능에 있어야 합니다.php?
  • 아니면 plugin base php 파일에 있을 수 있나요?(예: \wp-content\plugins\example\example.php)

이것을 명확하게 해주는 문서가 있습니까?

공식 문서인 https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/ 에는 언급되어 있지 않습니다.

마찬가지로 엔드포인트 함수는 어디에 저장해야 합니까?등록 기능은 경로를 지정하지 않고 이름만 지정합니다.

예를 들어, 다음과 같이 할 수 있습니다.

  • 등록기능 호출 (register_rest_route)은 메인 플러그인 파일(예: \wp-content\plugins\example\example.php)에 들어갑니다.
  • Endpoint 기능이 일부 다른 플러그인 파일(예: \wp-content\plugins\example\sub-path-stuff\example-controller.php)에 있습니다.

만약 그렇다면, 어떻게?

다음 링크는 이를 시도하는 것처럼 보이지만 이러한 특성(예: \wp-content\plugins\example\example.php)을 지정하지 않습니다.

따라서 register_rest_route는 "rest_api_init" 작업 후크 내부로 들어가며, 경로에 대한 콜백은 동일한 파일 또는 외부 파일에 정의될 수 있습니다(그러면 메인 파일 내부에서 요구하여 경로/s에 추가할 수 있습니다).예는 다음과 같습니다.

플러그인 "api-test"가 있다고 가정해 보겠습니다. 그것은 \wp-content\plugins\api-test에 배치되어 있고 우리는 api-test를 추가합니다.php를 메인 플러그인 파일로 사용합니다(이 예제에서는 기능적으로 opop이 될 것입니다).내부 api-test.php 당신은 다음과 같은 것을 가질 수 있습니다:

/**
 * @wordpress-plugin
 * Plugin Name: WP Rest api testing..
 */

/**
 * at_rest_testing_endpoint
 * @return WP_REST_Response
 */
function at_rest_testing_endpoint()
{
    return new WP_REST_Response('Howdy!!');
}

/**
 * at_rest_init
 */
function at_rest_init()
{
    // route url: domain.com/wp-json/$namespace/$route
    $namespace = 'api-test/v1';
    $route     = 'testing';

    register_rest_route($namespace, $route, array(
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => 'at_rest_testing_endpoint'
    ));
}

add_action('rest_api_init', 'at_rest_init');

이것은 모든 것이 동일한 파일에 있는 정말 간단한 예입니다.

언급URL : https://stackoverflow.com/questions/64327204/where-to-register-rest-route-to-wordpress-plugin-endpoint

반응형