wordpress rest api get post data by url only

Viewed 4279

is it possible to get post data/type from the wordpress rest api using url as parameter?

I knowing this function already from soundcloud. There is an resolve function with an url parameter (see https://developers.soundcloud.com/docs/api/reference#resolve). When you call this rest api endpoint, you get detailed information if the url is for example a track or playlist.

Unfortunately i couldn't find a function at the wordpress rest api documentation for doing this. What i exactly want is to get the post data/type by only knowing the url

With a function like this https://demo.wp-api.org/wp-json/wp/v2/resolve?url=https://demo.wp-api.org/2017/05/23/hello-world/

Is there a way to do this? Or do i need to write my own rest api endpoint with a wordpress plugin?

2 Answers

this solved the problem

function route_handler($request)
{
    global $wp;
    global $wp_query;
    $parameters = $request->get_json_params();
    $url = $parameters["url"];
    $_SERVER['REQUEST_URI'] = $url;
    $wp->parse_request();
    $wp->query_posts();
    //Insert queries for more specific information
    //Modify or simplify the query results
    //Here I'm just returning the query results.
    return json_encode($wp_query);
}
add_action('rest_api_init', function () {
    register_rest_route('custom-theme/v1', '/route', array(
        'methods' => 'POST',
        'callback' => 'route_handler',
    ));
});

see: https://medium.com/@harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7

You could just get all the posts https://demo.wp-api.org/wp-json/wp/v2/posts and then do some thing like:

$.each(data, function(index, post){
    if(post.link == yourUrl){
    //yourcode
    }
});

If you don't want to write your own endpoint

Related