WP_REST_Request::from_url() WordPress Method

The WP_REST_Request::from_url() method is used to construct a new WP_REST_Request object from a given URL. This is useful for making requests to the WordPress REST API from outside of WordPress.

WP_REST_Request::from_url( string $url ) #

Retrieves a WP_REST_Request object from a full URL.


Parameters

$url

(string)(Required)URL with protocol, domain, path and query args.


Top ↑

Return

(WP_REST_Request|false) WP_REST_Request object on success, false on failure.


Top ↑

Source

File: wp-includes/rest-api/class-wp-rest-request.php

	public static function from_url( $url ) {
		$bits         = parse_url( $url );
		$query_params = array();

		if ( ! empty( $bits['query'] ) ) {
			wp_parse_str( $bits['query'], $query_params );
		}

		$api_root = rest_url();
		if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
			// Pretty permalinks on, and URL is under the API root.
			$api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
			$route        = parse_url( $api_url_part, PHP_URL_PATH );
		} elseif ( ! empty( $query_params['rest_route'] ) ) {
			// ?rest_route=... set directly.
			$route = $query_params['rest_route'];
			unset( $query_params['rest_route'] );
		}

		$request = false;
		if ( ! empty( $route ) ) {
			$request = new WP_REST_Request( 'GET', $route );
			$request->set_query_params( $query_params );
		}

		/**
		 * Filters the REST API request generated from a URL.
		 *
		 * @since 4.5.0
		 *
		 * @param WP_REST_Request|false $request Generated request object, or false if URL
		 *                                       could not be parsed.
		 * @param string                $url     URL the request was generated from.
		 */
		return apply_filters( 'rest_request_from_url', $request, $url );
	}


Top ↑

Changelog

Changelog
VersionDescription
4.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.