W3cubDocs

/WordPress

rest_get_route_for_post( int|WP_Post $post )

Gets the REST API route for a post.

Parameters

$post

(int|WP_Post) (Required) Post ID or post object.

Return

(string) The route path with a leading slash for the given post, or an empty string if there is not a route.

Source

File: wp-includes/rest-api.php

function rest_get_route_for_post( $post ) {
	$post = get_post( $post );

	if ( ! $post instanceof WP_Post ) {
		return '';
	}

	$post_type = get_post_type_object( $post->post_type );
	if ( ! $post_type ) {
		return '';
	}

	$controller = $post_type->get_rest_controller();
	if ( ! $controller ) {
		return '';
	}

	$route = '';

	// The only two controllers that we can detect are the Attachments and Posts controllers.
	if ( in_array( get_class( $controller ), array( 'WP_REST_Attachments_Controller', 'WP_REST_Posts_Controller' ), true ) ) {
		$namespace = 'wp/v2';
		$rest_base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name;
		$route     = sprintf( '/%s/%s/%d', $namespace, $rest_base, $post->ID );
	}

	/**
	 * Filters the REST API route for a post.
	 *
	 * @since 5.5.0
	 *
	 * @param string  $route The route path.
	 * @param WP_Post $post  The post object.
	 */
	return apply_filters( 'rest_route_for_post', $route, $post );
}

Changelog

Version Description
5.5.0 Introduced.

© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/rest_get_route_for_post