rest_get_route_for_post

The timeline below displays how wordpress function rest_get_route_for_post has changed across different WordPress versions. If a version is not listed, refer to the next available version below.

WordPress Version: 5.9

/**
 * Gets the REST API route for a post.
 *
 * @since 5.5.0
 *
 * @param int|WP_Post $post 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.
 */
function rest_get_route_for_post($post)
{
    $post = get_post($post);
    if (!$post instanceof WP_Post) {
        return '';
    }
    $post_type_route = rest_get_route_for_post_type_items($post->post_type);
    if (!$post_type_route) {
        return '';
    }
    $route = sprintf('%s/%d', $post_type_route, $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);
}

WordPress Version: 5.5

/**
 * Gets the REST API route for a post.
 *
 * @since 5.5.0
 *
 * @param int|WP_Post $post 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.
 */
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);
}