简体   繁体   English

WordPress REST API插件开发-添加自定义端点

[英]WordPress REST API Plugin Development - Add Custom Endpoint

I'm almost certainly doing something stupid - or rather not doing something obvious that I should have done. 几乎可以肯定,我正在做一些愚蠢的事情-或者不是在做我应该做的明显事情。 I'm writing a plugin to expose a function via http POST so I can send JSON to my wordpress app and store it in the db. 我正在编写一个插件来通过http POST公开功能,因此我可以将JSON发送到我的wordpress应用程序并将其存储在数据库中。 I'm using the WP REST API plugin and have followed the "Adding custom endpoints" guide here http://v2.wp-api.org/extending/adding/ 我使用的是WP REST API插件,并且已在http://v2.wp-api.org/extending/adding/处遵循“添加自定义端点”指南

My plugin is as follows:- 我的插件如下:

# Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once(ABSPATH . 'wp-content/plugins/rest-api/plugin.php');
require_once(dirname(__FILE__) . '/classes/myPlugin.php');
require_once(dirname(__FILE__) . '/classes/myController.php');

// Action hook to initialize the plugin
add_action('rest_api_init', array('myPlugin_Class', 'init' ));

register_activation_hook(__FILE__, array('myPlugin_Class', 'on_activation'));
register_deactivation_hook(__FILE__, array('myPlugin_Class', 'on_deactivation'));
register_uninstall_hook(__FILE__, array('myPlugin_Class', 'on_uninstall'));

The myPlugin_Class is just an encapsulation of the main plugin bits... It holds a reference to a static class myController which extends WP_REST_Controller. myPlugin_Class只是主要插件位的封装...它包含对扩展WP_REST_Controller的静态类myController的引用。 The plugin class excerpt with its init method and constructor is as follows:- 插件类摘录及其初始化方法和构造函数如下:

class MyPlugin_Class
{
    private static $instance;
    private static $myController = null;

    public static function init()
    {
        if(self::$instance == null) {
           self::$instance = new MyPlugin_Class();
        }
        return self::$instance;
    }

    private function __construct()
    {
        Static::$myController = MyController::init();
        Static::$myController->register_routes();
        flush_rewrite_rules();
    }

    public static function on_activation()
    {
        Static::init();

        if ( ! current_user_can( 'activate_plugins' ) )
            return;
        $plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
        check_admin_referer( "activate-plugin_{$plugin}" );

        //Register routes and don't forget to flush
        $this->myController->register_routes();
        flush_rewrite_rules();
    }
}

The Controller class excerpt is as follows:- Controller类摘录如下:

class MyController extends WP_REST_Controller {

    private static $instance;
    private $namespace = 'api/vendor/v1';
    private $base = 'default';

    private function __construct(){
    }

    public static function init() {
        if(self::$instance == null) {
            self::$instance = new MyController();
        }
        return self::$instance;
    }

    /**
    * Register the routes for the objects of the controller.
    */
    public function register_routes() {
        $base = $this->default-base;
        register_rest_route( $this->namespace, '/' . $base, array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => array( $this, 'get_items' ),
                'permission_callback' => array( $this, 'get_items_permissions_check' ),
                'args'            => array(

                ),
            ),
            array(
                'methods'         => WP_REST_Server::CREATABLE,
                'callback'        => array( $this, 'create_item' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
                'args'            => $this->get_endpoint_args_for_item_schema( true ),
            ),
        ) );
    }
}

I cant get the routes to register. 我无法获得注册路线。 Upon activation, in the call to register_rest_route, I get the error:- 激活后,在对register_rest_route的调用中,出现错误:-

Fatal error: Call to a member function register_route() on null in .../wp-content/plugins/rest-api/plugin.php on line 92

The function register_route() from the REST API Plugin REST API插件中的函数register_route()

function register_rest_route( $namespace, $route, $args = array(), $override = false ) {

    /** @var WP_REST_Server $wp_rest_server */
    global $wp_rest_server;

    if ( isset( $args['callback'] ) ) {
        // Upgrade a single set to multiple
        $args = array( $args );
    }

    $defaults = array(
        'methods'         => 'GET',
        'callback'        => null,
        'args'            => array(),
    );
    foreach ( $args as $key => &$arg_group ) {
        if ( ! is_numeric( $arg_group ) ) {
            // Route option, skip here
            continue;
        }

        $arg_group = array_merge( $defaults, $arg_group );
    }

    if ( $namespace ) {
        $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
    } else {
        // Non-namespaced routes are not allowed, with the exception of the main
        // and namespace indexes. If you really need to register a
        // non-namespaced route, call `WP_REST_Server::register_route` directly.
        _doing_it_wrong( 'register_rest_route', 'Routes must be namespaced with plugin name and version', 'WPAPI-2.0' );

        $full_route = '/' . trim( $route, '/' );
    }

    $wp_rest_server->register_route( $namespace, $full_route, $args, $override );
}

Where does this global $wp_rest_server get created (or in my case not created)? 该全局$ wp_rest_server在哪里创建(或者在我的情况下未创建)?

ie what did I forget to do? 即我忘了做什么?

Bonus question:- 奖励问题:

Should I call the flush_rewrite_rules() in the rest_api_init hook, the register_activation_hook or both? 我应该在rest_api_init钩子,register_activation_hook还是这两者中调用flush_rewrite_rules()?

Your call to add_action('rest_api_init', array('myPlugin_Class', 'init' )); 您对add_action('rest_api_init', array('myPlugin_Class', 'init' ));调用add_action('rest_api_init', array('myPlugin_Class', 'init' )); is very late and before that plugin activation hook 太晚了,在该插件激活挂钩之前

register_activation_hook(__FILE__, array('myPlugin_Class', 'on_activation'));

is gettting called. 被叫。 Hence null. 因此为空。

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

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