wordpress - 如何创建自定义 api 端点?

标签 wordpress

我是 WordPress 插件开发新手。我目前正在尝试开发一个加法计算器插件,其 API 端点位于 example.com/calc/add。如何将新的 URL 端点添加到我的 WordPress 安装中,以便插件可以接受“POST”请求(以逗号分隔的列表中的数字)并在添加数字后相应地返回数据?非常感谢!

最佳答案

您可以使用 parse_request 钩子(Hook)来创建端点,下面是我的插件之一的示例

// this example creates endpoint like http://emerico.in/api/v2

add_action('parse_request', 'endpoint', 0);
add_action('init', 'add_endpoint');

/**
 * @param null
 * @return null
 * @description Create a independent endpoint
 */
function endpoint()
{
    global $wp;

    $endpoint_vars = $wp->query_vars;

    // if endpoint
    if ($wp->request == 'api/v2') {

        // Your own function to process end pint
        $this->processEndPoint($_REQUEST);

        // After all redirect to home page
        wp_redirect(home_url());
        exit;
    } elseif (isset($endpoint_vars['tracking']) && !empty($endpoint_vars['tracking'])) {
        $request = [
            'tracking_id' => $endpoint_vars['tracking']
        ];

        $this->processEndPoint($request);
    } elseif (isset($_GET['utm_source']) && !empty($_GET['utm_source'])){
        $this->processGoogleTracking($_GET);
    }
}

/**
 * @param null
 * @return null
 * @description Create a permalink endpoint for projects tracking
 */
function add_endpoint()
{

    add_rewrite_endpoint('tracking', EP_PERMALINK | EP_PAGES, true);

}

关于wordpress - 如何创建自定义 api 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563364/

相关文章:

通过 SSL 提供服务时,Wordpress CSS 在 Chrome 中中断

javascript - WordPress - 无法在页面中找到 JS 代码片段

css - 我的CSS有什么问题?事件链接不改变颜色

php - WordPress 服务器不断耗尽内存并崩溃,我该如何确定并修复原因?

javascript - Joomla 有像 Wordpress 这样的简码吗?

mysql - 如何将相同的列值分组并映射到具有相应帖子值的新列

css - 为什么开发人员在 float 元素时使用负 margin ?

php - 无法将背景图像添加到 wordpress php 中的上一篇文章/下一篇文章按钮

php - WordPress插件开发中如何手动获取帖子缩略图URL?

php - 谷歌是否抓取/索引 "computed"或原始html源?