varsitynewsnetwork / wordpress-rest-api-client

A Wordpress API client for PHP
76 stars 64 forks source link

Create custom endpoints #29

Open str opened 4 years ago

str commented 4 years ago

I'm trying to create my custom end point but it looks like the endpoints are hardcoded to be classess form the Vnn\WpApiClient\Endpoint namespace;

What's the easiest way to define a custom endpoint?

jhhazelaar commented 3 years ago

Did you manage to add a custom end-point? We need it to add custom post types to WP

jhhazelaar commented 3 years ago

I think we need this #20

morban commented 3 years ago

Yes it will be very interesting.

zack-carlson commented 1 year ago

Hello.

Go into /vendor/vnn/wordpress-rest-api/src/Endpoints and copy "Posts" class to your main app directory and rename the class to CustomPostType and update namespace appropriately. Then when you call, you'll need to do it slightly different..

So in your "GetWPApiData" class (for example) .. in a method you need to get custom endpoint data, include your class CustomPostType in the "use" area, make sure it implements "AbstractWpEndpoint" ..

protected function getEndpoint()
    {
        return '/wp-json/wp/v2/mycustomendpoint';
    }

Then initiate

$custom_post_type_data = new CustomPostType($this->client);

return $custom_post_type_data->get();

Works great, don't have to fork or override private properties.

pekka commented 1 year ago

Works great, don't have to fork or override private properties.

Lovely - much better than hacking away in the package, then losing changes on updating... thank you!

angelxmoreno commented 1 year ago

Any ideas why the PR was not merged? it seems like a reasonable feature. @zack-carlson could you add the feature to the readme? something like this: https://wprestclient.readthedocs.io/en/latest/extending/api-prefix/

zack-carlson commented 1 year ago

@angelxmoreno I'm not sure the approach is what the maintainer wished for, but would be happy to copy the comment / explanation

<?php

namespace App\WpApiClient;

use Vnn\WpApiClient\Endpoint\AbstractWpEndpoint;

/**
 * Class Posts
 * @package Vnn\WpApiClient\Endpoint
 */
class Promotion extends AbstractWpEndpoint
{
    /**
     * {@inheritdoc}
     */
    protected function getEndpoint()
    {
        return '/wp-json/wp/v2/promotion';
    }
}
angelxmoreno commented 1 year ago

That's cool @zack-carlson

BTW, I ended up creating my own, WPRestClient because there was no license usage. The docs I linked were from my lib. I just wanted to promote the contribution of this lib since it served as an inspiration for creating WPRestClient