首页 > 解决方案 > add_action 在插件 activate() 中不起作用 使用 wordpress 插件样板的方法

问题描述

我正在尝试添加自定义端点(自定义端点”是指 WP 无法识别为标准 URL 的任意 URL,例如永久链接左右。)我使用 WordPress 插件样板” https://github.com/DevinVinson/WordPress-Plugin -样板“。

我想在自定义端点上发送 API 请求。我创建了一个新的类文件来注册端点并将这个类文件包含在插件激活方法中并调用 add_action 钩子,但它不起作用。

在包含文件夹中创建一个新的 class-rigal-custom-Endpoint.php 文件。

<?php

class Rigal_custom_Endpoint {

   private static $initiated = false;

    public static function init() {

        if ( ! self::$initiated ) {
            self::init_hooks();
        }
    }


    public static function init_hooks() {
        self::$initiated = true;
        add_action('init', 'add_endpoint');
    }
/**
 *
 * @description Create a independent endpoint
 */
public static function endpoint() {
    global $wp;
    $endpoint_vars = $wp->query_vars;
    // if endpoint
    if ($wp->request == 'exercise/test') {
        // Your own function to process endpoint
        exit;
    }
}
}

在我将这个类文件包含在插件激活方法中之后。(class-rigal-plugin-activator.php)

public static function activate() {

        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-rigal-custom-endpoint.php';

        add_action( 'init', array( 'Rigal_custom_Endpoint', 'init' ) );
                add_action( 'parse_request', array( 'Rigal_custom_Endpoint', 'endpoint' ) , 0);

    }

当我激活插件并在 URL 中添加“锻炼/测试”但它不起作用时。您能否提出解决上述问题的解决方案?

环境 PHP:7.4 Wordpress:5.4 操作系统:Mac:10.15.1 浏览器:Chrome:版本 81.0.4044.122

谢谢

标签: phpwordpress

解决方案


因为激活方法只在插件激活过程中执行。一旦插件被激活,这个方法将不再被执行。

class-plugin-name.phponload_dependencies方法中,添加您的类,例如:

require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-rigal-custom-endpoint.php';

define_public_hooks 添加您的操作

$this->loader->add_action( 'parse_request',  'Rigal_custom_Endpoint', 'endpoint' );

这将起作用,但考虑到您没有以标准方式注册端点 api。您应该查看 WP REST API 文档:
https ://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

这是使用 register_rest_route 的最小插件示例


<?php
/*
Plugin Name: Add WP Custom endpoint
Author: Robin Ferrari
Version: 1.0
*/

class MYPLUGIN_Api_Endpoint{
    public function init(){
        add_action( 'rest_api_init', array($this, 'register_rest_routes'));
    }
    public function register_rest_routes(){
        register_rest_route( 'myplugin/v1', '/exercise/test', array(
            'methods' => 'GET',
            'callback' => array($this, 'exercise_test'),
        ));
    }
    /**
     * Your custom route callback
     */
    public function exercise_test(){
        $error = false;
        // do what you whant
        if($error){
            return new WP_Error(500, "KO");
        }
        return new WP_Rest_Response(array(
            'status' => 200,
            'message' => "OK",
        ));
    }
}
$api = new MYPLUGIN_Api_Endpoint();
$api->init();

然后可以在此处访问您的端点:

https://example.com/wp-json/myplugin/v1/exercise/test

推荐阅读