A WordPress-centric search engine for devs and theme authors



rest_get_route_for_post ›

Since5.5.0
Deprecatedn/a
rest_get_route_for_post ( $post )
Parameters:
  • (int|WP_Post) $post Post ID or post object.
    Required: Yes
Returns:
  • (string) The route path with a leading slash for the given post, or an empty string if there is not a route.
Defined at:
Codex:

Gets the REST API route for a post.



Source

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 );
}