简体   繁体   中英

Wordpress API - link to full post details from list of posts

I have installed the Wordpress API onto on of our company websites so that we can retrieve data from it to display on a new company website. With regards to grabbing and displaying the initial data all works fine (posts from a specific category from the original website onto a specific page on the new website).

This is for a events that are input onto a 'whats on' page on the existing website that take place at a bar/restaurant. The new site is purely dedicated to the events and to save having to add/amend the events on both sites we thought it best to use the API.

To retrieve the full listing of events (which works) I use:

$response = wp_remote_get( 'http://restuarantdomain.com/wp-json/wp/v2/posts?filter[category_name]=live-events&per_page=50' );

I also know that to display an individual post I need to use:

$response = wp_remote_get( 'http://restaurantdomain.com/wp-json/wp/v2/posts?filter[name]=event_name );

What I can't work out how to do is create a 'friendly' url on the new site that will then go to a page that calls the function to get the individual post details.

For example I want the url http://eventdomain.com/whats-on/event-name (in the list of event posts grabbed through the 1st API call above) to go to the page What's On and on that page use the event-name from the url as the parameter in the 2nd API call above. But Wordpress just looks for the category and post name due to the format of the url which don't exist so I just get a 404.

What am I missing?

You must create your custom Endpoints.

for instance, if you want to filter all posts within a particular category you should do this

function my_cat_func( $data ) {
    $posts = get_posts( array(
        'cat' => $data['id'],
    ) );

    if ( empty( $posts ) ) {
        return null;
    }

    return $posts[0]->post_title;
}

then you must add an action to register your endpoint call

add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v2', '/categoy/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_cat_func',
    ) );
} );

then you will get something like this

http://example.com/wp-json/myplugin/v2/categoy/(?P<id>\d+)

for more information and better understanding, I suggest you reading this reference: http://v2.wp-api.org/extending/adding/

This article also can give you more example: https://webdevstudios.com/2015/07/09/creating-simple-json-endpoint-wordpress/ and https://deliciousbrains.com/wp-rest-api-customizing-endpoints-adding-new-ones/

Note: I wrote this code on the fly, that should need more efforts to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM