Make WordPress Core


Ignore:
Timestamp:
02/24/2016 04:00:12 AM (7 years ago)
Author:
rmccue
Message:

REST API: Add WP_REST_Request::from_url()

Allows converting a REST URL into a Request object.

Props danielbachhuber.
Fixes #35803.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/class-wp-rest-request.php

    r36636 r36673  
    935935        }
    936936    }
     937
     938    /**
     939     * Gets a WP_REST_Request object from a full URL.
     940     *
     941     * @since 4.5.0
     942     *
     943     * @param string $url URL with protocol, domain, path and query args.
     944     * @return WP_REST_Request|false WP_REST_Request object on success, false on failure.
     945     */
     946    public static function from_url( $url ) {
     947        $bits = parse_url( $url );
     948        $query_params = array();
     949
     950        if ( ! empty( $bits['query'] ) ) {
     951            wp_parse_str( $bits['query'], $query_params );
     952        }
     953
     954        $api_root = rest_url();
     955        if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
     956            // Pretty permalinks on, and URL is under the API root
     957            $api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
     958            $route = parse_url( $api_url_part, PHP_URL_PATH );
     959        } elseif ( ! empty( $query_params['rest_route'] ) ) {
     960            // ?rest_route=... set directly
     961            $route = $query_params['rest_route'];
     962            unset( $query_params['rest_route'] );
     963        }
     964
     965        $request = false;
     966        if ( ! empty( $route ) ) {
     967            $request = new WP_REST_Request( 'GET', $route );
     968            $request->set_query_params( $query_params );
     969        }
     970
     971        /**
     972         * Filter the request generated from a URL.
     973         *
     974         * @since 4.5.0
     975         *
     976         * @param WP_REST_Request|false $request Generated request object, or false if URL could not be parsed.
     977         * @param string $url URL the request was generated from.
     978         */
     979        return apply_filters( 'rest_request_from_url', $request, $url );
     980    }
    937981}
Note: See TracChangeset for help on using the changeset viewer.