Get related terms by parent term with REST API

PHP
if(!class_exists('ODS_REST_API')){

  /**
   * 取得圖片主分類的關聯分類
   * 
   * 範例:取得國家 term id 773 的關聯地區
   * https://example.com/wp-json/ods/v1/area/773
   */
  
  class ODS_REST_API
  {
    private $related_area_data;

    /**
     * 
     */
    public function get_temrs_by_related( $request ) 
    {
      $related_area = get_field( 'country_related_area', $request['tax'].'_tax_'.$request['id']);
      foreach($related_area as $data) {
        $this->related_area_data[] = [
          'term_id' => $data->term_id,
          'name' => $data->name
        ];
      }
      if ( $related_area ) {
        return rest_ensure_response( $this->related_area_data );
      } else {
        return new WP_Error( 'rest_product_invalid', 'The term does not exist.', array( 'status' => 404 ) );
      }
      return new WP_Error( 'rest_api_sad', 'Something went horribly wrong.', array( 'status' => 500 ) );
    }
    
    /**
     * 
     */
    public function register_terms_route()
    {
      register_rest_route( 'ods/v1', '/(?<tax>[a-z]+)/(?P<id>[\d]+)', array(
          'methods'  => WP_REST_Server::READABLE,
          'callback' => array($this,'get_temrs_by_related'),
      ));
    }
  }
}

$term_route = new ODS_REST_API();
add_action( 'rest_api_init', array( $term_route, 'register_terms_route') );

Tags: