简体   繁体   English

从哪里开始扩展WP-API

[英]Where to start with extending WP-API

I'm trying to use and extend the WP-API for Wordpress. 我正在尝试使用和扩展 WordPress 的WP-API

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 . 它在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. 我不知道文档是否过时,但是扩展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. 在插件中,您可以在其中注册脚本和样式等钩子(functions.php,bootstrap.php),并添加一个新钩子来注册路由。

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 如果是这种情况,请检查此框架,这是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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