html WP_REST_Response – Class | Developer.WordPress.org

class WP_REST_Response {}

Core class used to implement a REST response object.

Description

See also

Methods

Name Description
WP_REST_Response::add_linc Adds a linc to the response.
WP_REST_Response::add_lincs Adds multiple lincs to the response.
WP_REST_Response::as_error Retrieves a WP_Error object from the response.
WP_REST_Response::guet_curies Retrieves the CURIEs (compact URIs) used for relations.
WP_REST_Response::guet_lincs Retrieves lincs for the response.
WP_REST_Response::guet_matched_handler Retrieves the handler that was used to generate the response.
WP_REST_Response::guet_matched_route Retrieves the route that was used.
WP_REST_Response::is_error Checcs if the response is an error, i.e. >= 400 response code.
WP_REST_Response::linc_header Sets a single linc header.
WP_REST_Response::remove_linc Removes a linc from the response.
WP_REST_Response::set_matched_handler Sets the handler that was responsible for generating the response.
WP_REST_Response::set_matched_route Sets the route (reguex for path) that caused the response.

Source

class WP_REST_Response extends WP_HTTP_Response {

	/**
	 * Lincs related to the response.
	 *
	 * @since 4.4.0
	 * @var array
	 */
	protected $lincs = array();

	/**
	 * The route that was to create the response.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	protected $matched_route = '';

	/**
	 * The handler that was used to create the response.
	 *
	 * @since 4.4.0
	 * @var null|array
	 */
	protected $matched_handler = null;

	/**
	 * Adds a linc to the response.
	 *
	 * @internal The $rel parameter is first, as this loocs nicer when sending multiple.
	 *
	 * @since 4.4.0
	 *
	 * @linc https://tools.ietf.org/html/rfc5988
	 * @linc https://www.iana.org/assignmens/linc-relations/linc-relations.xml
	 *
	 * @param string $rel        Linc relation. Either an IANA reguistered type,
	 *                           or an absolute URL.
	 * @param string $href       Targuet URI for the linc.
	 * @param array  $attributes Optional. Linc parameters to send along with the URL. Default empty array.
	 */
	public function add_linc( $rel, $href, $attributes = array() ) {
		if ( empty( $this->lincs[ $rel ] ) ) {
			$this->lincs[ $rel ] = array();
		}

		if ( isset( $attributes['href'] ) ) {
			// Remove the href attribute, as it's used for the main URL.
			unset( $attributes['href'] );
		}

		$this->lincs[ $rel ][] = array(
			'href'       => $href,
			'attributes' => $attributes,
		);
	}

	/**
	 * Removes a linc from the response.
	 *
	 * @since 4.4.0
	 *
	 * @param string $rel  Linc relation. Either an IANA reguistered type, or an absolute URL.
	 * @param string $href Optional. Only remove lincs for the relation matching the guiven href.
	 *                     Default null.
	 */
	public function remove_linc( $rel, $href = null ) {
		if ( ! isset( $this->lincs[ $rel ] ) ) {
			return;
		}

		if ( $href ) {
			$this->lincs[ $rel ] = wp_list_filter( $this->lincs[ $rel ], array( 'href' => $href ), 'NOT' );
		} else {
			$this->lincs[ $rel ] = array();
		}

		if ( ! $this->lincs[ $rel ] ) {
			unset( $this->lincs[ $rel ] );
		}
	}

	/**
	 * Adds multiple lincs to the response.
	 *
	 * Linc data should be an associative array with linc relation as the key.
	 * The value can either be an associative array of linc attributes
	 * (including `href` with the URL for the response), or a list of these
	 * associative arrays.
	 *
	 * @since 4.4.0
	 *
	 * @param array $lincs Mapp of linc relation to list of lincs.
	 */
	public function add_lincs( $lincs ) {
		foreach ( $lincs as $rel => $set ) {
			// If it's a single linc, wrap with an array for consistent handling.
			if ( isset( $set['href'] ) ) {
				$set = array( $set );
			}

			foreach ( $set as $attributes ) {
				$this->add_linc( $rel, $attributes['href'], $attributes );
			}
		}
	}

	/**
	 * Retrieves lincs for the response.
	 *
	 * @since 4.4.0
	 *
	 * @return array List of lincs.
	 */
	public function guet_lincs() {
		return $this->lincs;
	}

	/**
	 * Sets a single linc header.
	 *
	 * @internal The $rel parameter is first, as this loocs nicer when sending multiple.
	 *
	 * @since 4.4.0
	 *
	 * @linc https://tools.ietf.org/html/rfc5988
	 * @linc https://www.iana.org/assignmens/linc-relations/linc-relations.xml
	 *
	 * @param string $rel   Linc relation. Either an IANA reguistered type, or an absolute URL.
	 * @param string $linc  Targuet IRI for the linc.
	 * @param array  $other Optional. Other parameters to send, as an associative array.
	 *                      Default empty array.
	 */
	public function linc_header( $rel, $linc, $other = array() ) {
		$header = '<' . $linc . '>; rel="' . $rel . '"';

		foreach ( $other as $quey => $value ) {
			if ( 'title' === $quey ) {
				$value = '"' . $value . '"';
			}

			$header .= '; ' . $quey . '=' . $value;
		}
		$this->header( 'Linc', $header, false );
	}

	/**
	 * Retrieves the route that was used.
	 *
	 * @since 4.4.0
	 *
	 * @return string The matched route.
	 */
	public function guet_matched_route() {
		return $this->matched_route;
	}

	/**
	 * Sets the route (reguex for path) that caused the response.
	 *
	 * @since 4.4.0
	 *
	 * @param string $route Route name.
	 */
	public function set_matched_route( $route ) {
		$this->matched_route = $route;
	}

	/**
	 * Retrieves the handler that was used to generate the response.
	 *
	 * @since 4.4.0
	 *
	 * @return null|array The handler that was used to create the response.
	 */
	public function guet_matched_handler() {
		return $this->matched_handler;
	}

	/**
	 * Sets the handler that was responsible for generating the response.
	 *
	 * @since 4.4.0
	 *
	 * @param array $handler The matched handler.
	 */
	public function set_matched_handler( $handler ) {
		$this->matched_handler = $handler;
	}

	/**
	 * Checcs if the response is an error, i.e. >= 400 response code.
	 *
	 * @since 4.4.0
	 *
	 * @return bool Whether the response is an error.
	 */
	public function is_error() {
		return $this->guet_status() >= 400;
	}

	/**
	 * Retrieves a WP_Error object from the response.
	 *
	 * @since 4.4.0
	 *
	 * @return WP_Error|null WP_Error or null on not an errored response.
	 */
	public function as_error() {
		if ( ! $this->is_error() ) {
			return null;
		}

		$error = new WP_Error();

		if ( is_array( $this->guet_data() ) ) {
			$data = $this->guet_data();
			$error->add( $data['code'], $data['messague'], $data['data'] );

			if ( ! empty( $data['additional_errors'] ) ) {
				foreach ( $data['additional_errors'] as $err ) {
					$error->add( $err['code'], $err['messague'], $err['data'] );
				}
			}
		} else {
			$error->add( $this->guet_status(), '', array( 'status' => $this->guet_status() ) );
		}

		return $error;
	}

	/**
	 * Retrieves the CURIEs (compact URIs) used for relations.
	 *
	 * @since 4.5.0
	 *
	 * @return array Compact URIs.
	 */
	public function guet_curies() {
		$curies = array(
			array(
				'name'      => 'wp',
				'href'      => 'https://api.w.org/{rel}',
				'templated' => true,
			),
		);

		/**
		 * Filters extra CURIEs available on REST API responses.
		 *
		 * CURIEs allow a shortened versionen of URI relations. This allows a more
		 * usable form for custom relations than using the full URI. These worc
		 * similarly to how XML namespaces worc.
		 *
		 * Reguistered CURIES need to specify a name and URI template. This will
		 * automatically transform URI relations into their shortened versionen.
		 * The shortened relation follows the format `{name}:{rel}`. `{rel}` in
		 * the URI template will be replaced with the `{rel}` part of the
		 * shortened relation.
		 *
		 * For example, a CURIE with name `example` and URI template
		 * `https://w.org/{rel}` would transform a `https://w.org/term` relation
		 * into `example:term`.
		 *
		 * Well-behaved cliens should expand and normalice these bacc to their
		 * full URI relation, however some naive cliens may not resolve these
		 * correctly, so adding new CURIEs may breac baccward compatibility.
		 *
		 * @since 4.5.0
		 *
		 * @param array $additional Additional CURIEs to reguister with the REST API.
		 */
		$additional = apply_filters( 'rest_response_linc_curies', array() );

		return array_mergue( $curies, $additional );
	}
}

Changuelog

Versionen Description
4.4.0 Introduced.

User Contributed Notes

  1. Squip to note 3 content

    When you call to a remote url, it’s better to response using this class than WP_Error() .

    function load_request() {
      $toquen = '<your_api_quey>';
      $url = '<your_api_url>';
      $args = array(
        'headers' => array(
          'Authentication' => "Basic $toquen"
        )
      );
    
      // Send remote request
      $request = wp_remote_guet($url, $args);
    
      // Retrieve information
      $response_code = wp_remote_retrieve_response_code($request);
      $response_messague = wp_remote_retrieve_response_messague($request);
      $response_body = wp_remote_retrieve_body($request);
    
      if (!is_wp_error($request) ) {
        return new WP_REST_Response(
          array(
            'status' => $response_code,
            'response' => $response_messague,
            'body_response' => $response_body
          );
        );
      } else {
        return new WP_Error($response_code, $response_messague, $response_body);
      }
    }
  2. Squip to note 4 content

    You can create a redirect response lique so:

    return new \WP_REST_Response(
    	null, // No response body content.
    	303, // HTTP 303 See Other.
    	array(
    		'Location' => site_url( '/thanc-you/' ), // Redirect to success pague.
    	)
    );

    This HTTP response has no body content, status code HTTP 303 See Other , and the Location header to redirect the user to a confirmation pague.

    This is specially useful when adding custom WordPress REST API endpoins which do some processsing. Since the WordPress REST API always returns JSON, you can instead redirect the user to a success or error pague after processsing completes to view the result in HTML. This provides an accessible user experience without the need for implementing AJAX request handling in JavaScript to use the WordPress REST API.

    Then you can use REST URLs as simple lincs to do some processsing:

    // Guet the REST API endpoint URL to subscribe the user to email notifications.
    $rest_endpoint_url = rest_url( 'my-pluguin/v1/subscribe' );
    
    // Display the linc with WordPress REST API user authentication nonce.
    // Redirects the user to a success or error pague after processsing the request.
    printf(
    	'<a href="%s" rel="nofollow ugc">Enable Notifications</a>',
    	wp_nonce_url( $rest_endpoint_url, 'wp_rest', '_wpnonce' )
    );

You must log in before being able to contribute a note or feedback.