创建自定义WordPress API插件示例-PHP语言论坛-编程语言区-资源工坊-游戏模组资源分享

创建自定义WordPress API插件示例

代码示例

新建一个php格式文件将下面代码保存,新建文件夹放入php文件打包成zip格式压缩包,在后台上传插件安装即可

<?php
/**
 * Plugin Name: API插件
 * Description: 一个的WordPress API插件,用于满足你的需求。
 */

// 导入必要的库
require_once ABSPATH . WPINC . '/pluggable.php';

// 注册插件设置页
function custom_api_plugin_settings_page() {
    // 添加菜单页面,这个页面将允许管理员配置API设置
    add_menu_page(
        'API设置',           // 页面标题
        'API设置',           // 菜单标题
        'manage_options',     // 用户权限(管理员权限)
        'custom-api-settings', // 菜单页面的标识符
        'custom_api_plugin_settings_page_content' // 回调函数,用于渲染页面内容
    );
}

// 在管理菜单中添加设置页面
add_action('admin_menu', 'custom_api_plugin_settings_page');

// 设置页面内容
function custom_api_plugin_settings_page_content() {
    // 处理表单提交,如果管理员改变API状态,将其保存
    if (isset($_POST['api_enabled'])) {
        $api_enabled = (int) $_POST['api_enabled'];
        // 更新选项以保存API状态
        update_option('custom_api_enabled', $api_enabled);
    }

    // 获取当前API状态
    $api_enabled = get_option('custom_api_enabled', 0);

    ?>
    <div class="wrap">
        <h2>API设置</h2>
        <form method="post" action="">
            <label for="api_enabled">启用API:</label>
            <input type="checkbox" name="api_enabled" id="api_enabled" value="1" <?php checked(1, $api_enabled); ?> />
            <p>勾选以启用API功能,取消勾选以禁用。</p>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

// 添加API开关字段
function aopk_user_account_enabled() {
    // 获取API状态选项的值,如果为1表示启用,0表示禁用
    $api_enabled = get_option('custom_api_enabled', 0);
    return $api_enabled;
}

// 注册API路由,仅当API启用时才注册路由
add_action('rest_api_init', function () {
    if (aopk_user_account_enabled()) {
        // 仅当API启用时才注册路由
        register_rest_route('/v1', '/get-user-account', array(
            'methods' => 'GET',
            'callback' => 'aopk_user_account',
        ));
    }
});

// 用户ID>获取用户账号
function aopk_user_account($request) {
    // 从请求参数中获取用户ID
    $user_id = $request->get_param('user_id');
    $user_account = get_user_account($user_id);

    // 创建响应数组
    $response_data = array();

    if ($user_account) {
        $response_data['success'] = true;
        $response_data['user_account'] = $user_account;
        $response_code = 200;
    } else {
        $response_data['success'] = false;
        $response_data['error'] = '用户不存在';
        $response_code = 404;
    }

    // 将响应数组转换为JSON格式
    $response = new WP_REST_Response($response_data, $response_code);
    $response->set_headers(array('Content-Type' => 'application/json'));

    return $response;
}

function get_user_account($user_id) {
    // 获取用户账号,如果用户不存在,返回false
    $user_info = get_userdata($user_id);
    if (!$user_info) {
        return false;
    }
    $user_account = $user_info->user_login;
    return $user_account;
}

请求地址

https://你的域名/wp-json/v1/get-user-account?user_id=用户ID

user_id便是传入参数

请登录后发表评论

    没有回复内容