简体   繁体   中英

Where to start with extending WP-API

I'm trying to use and extend the WP-API for Wordpress.

Now I might just be stupid but I really can't figure out where to start even though I've read the link above over and over. And I'm not talking code-wise but the very basics, where do I put the code? In a plugin? If so, what do I need to include to get it to work? Or is it enough to extend the class?

Sorry but I just find the info on the page to be way too little... Or have I totaly missed an perfectly structured example from top to bottom?

Here it is on GitHub . Thanks for any help!

I don't know if the documentation was out of date or something but it's pretty simple to extend WP-API. You'll need to write a plugin first.

In the plugin, where you register the hooks like scripts and styles (functions.php, bootstrap.php) you add a new hook to register the routes.

add_filter( 'json_endpoints', array( $this, 'registerRoutes' ) );

public function registerRoutes($routes){
        $editorService = $this->container["editorService"];

        $routes['/newsletters'] = array(
            array( array( $editorService, 'create'), \WP_JSON_Server::CREATABLE | \WP_JSON_Server::ACCEPT_JSON ),
        );
        $routes['/newsletters/(?P<id>\d+)'] = array(
            array( array( $editorService, 'get'), \WP_JSON_Server::READABLE )
        );
        return $routes;
    }

If you read the documentation you'll see that newsletter is the entity. In this example i inject a service and call it in the routes. Very probably you use a different approach and if you've difficulties in this point you'll have to figure out how to structure the plugin, which patterns apply, write or not your own framework, etc.

If thats the case check this skeleton, it's a great approach to MVC https://github.com/iandunn/WordPress-Plugin-Skeleton

If you want to call a function inside the same class you would do:

public function registerRoutes(){
    $routes['/newsletters'] = array(
        array( array( $this, 'createNewsletter'), \WP_JSON_Server::CREATABLE | \WP_JSON_Server::ACCEPT_JSON )
    );
}
public function createNewsletter() {
    $wpdb->prepare(); // etc etc
}

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