钩子文档

rest_url_prefix

💡 云策文档标注

概述

rest_url_prefix 是一个 WordPress 过滤器,用于修改 REST API 的 URL 前缀。默认前缀为 'wp-json',开发者可以通过此 Hook 自定义前缀,如改为 'api'。

关键要点

  • rest_url_prefix 过滤器允许修改 REST API 的 URL 前缀,参数为字符串类型,默认值为 'wp-json'。
  • 更改前缀后,必须刷新重写规则,最简单的方法是访问后台的“设置/固定链接”并保存现有设置。
  • 相关函数 rest_get_url_prefix() 可用于检索 API 资源的 URL 前缀。

代码示例

add_filter( 'rest_url_prefix', function () {
    return 'api';
} );

注意事项

更改前缀后,新的 REST API URL 将变为 example.com/api/,而不是默认的 example.com/wp-json/。


📄 原文内容

Filters the REST URL prefix.

Parameters

$prefixstring
URL prefix. Default 'wp-json'.

Source

return apply_filters( 'rest_url_prefix', 'wp-json' );

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    If you want to change WordPress’s default REST API URL prefix from wp-json to another prefix e.g. api add the following code to your theme’s functions.php file or in a custom plugin:

    add_filter( 'rest_url_prefix', function () {
        return 'api';
    } );

    Now, refresh rewrite rules by going to Settings -> Permalinks and hit Save Changes.

    Your new REST API URL will be example.com/api/ instead of the default example.com/wp-json/.