目錄
Use register_rest_field() for Custom Data
Use register_meta() for Post or User Meta
Test Your New Field in the REST API
Permissions and Security
首頁 CMS教程 &#&按 如何為REST API註冊自定義字段

如何為REST API註冊自定義字段

Aug 06, 2025 am 04:18 AM

要向WordPress的REST API添加自定義字段,需使用register_rest_field()或register_meta()。 1. 使用register_rest_field()處理非元數據的自定義數據,通過rest_api_init鉤子註冊字段,並定義get_callback、update_callback及權限控制;2. 使用register_meta()暴露存儲在post meta或user meta中的字段,只需設置show_in_rest為true;3. 測試新字段時訪問站點的REST API端點,確保代碼生效並檢查權限設置。兩種方法均需注意刷新規則和權限配置以確保字段正確顯示和訪問。

To add a custom field to the REST API in WordPress, you need to register it using a filter or function. The most common way is with register_rest_field() or register_meta() , depending on what kind of data you're working with and where it's stored.

Here's how to do it step by step.


Use register_rest_field() for Custom Data

If your custom field isn't already part of the post meta or user meta system — say, it's calculated or pulled from somewhere else — use register_rest_field() . This gives you full control over how and when the data is retrieved and updated.

You'll typically hook into rest_api_init so your field gets registered when the REST API starts up.

 add_action( 'rest_api_init', function () {
    register_rest_field( 'post', 'custom_data', array(
        'get_callback' => 'get_custom_data',
        'update_callback' => 'update_custom_data',
        'schema' => null,
    ));
});
  • 'post' means this will apply to posts. You can also use 'user' , 'comment' , or any custom post type.
  • 'custom_data' is the name of the new field that will appear in the API response.
  • get_callback defines how the value is fetched.
  • update_callback handles updates (optional if you don't want the field to be editable).

Example get callback:

 function get_custom_data( $object, $field_name, $request ) {
    return get_post_meta( $object['id'], '_custom_key', true );
}

Use register_meta() for Post or User Meta

If your custom field lives in the post meta or user meta table, register_meta() is usually better. It automatically adds the field to the REST API if configured properly.

For example, to expose a _custom_key meta field for posts:

 register_meta( 'post', '_custom_key', array(
    'type' => 'string',
    'description' => 'A custom text field',
    'single' => true,
    'show_in_rest' => true,
));

This approach is cleaner and avoids writing extra callbacks unless needed.

If you're registering for users instead of posts, just change 'post' to 'user' .

Note: If you're using Advanced Custom Fields (ACF), make sure to set 'show_in_rest' => true in your ACF field group settings for the fields you want exposed.


Test Your New Field in the REST API

Once you've added the code, check your site's REST API endpoint to see if the field shows up. For posts, go to:

 https://yoursite.com/wp-json/wp/v2/posts

Click on a specific post, and you should see your custom field there.

If not:

  • Make sure the code is active (in your theme's functions.php or a plugin).
  • Check for syntax errors.
  • Flush rewrite rules by visiting Settings > Permalinks and clicking Save.

Permissions and Security

By default, some fields may only show up if you're logged in or have the right capabilities. If you want your custom field to be publicly accessible, make sure to set permissions correctly.

For register_rest_field() , you can add a permission callback:

 'permission_callback' => function () {
    return current_user_can( 'edit_posts' );
},

Or for public read access:

 'permission_callback' => '__return_true',

Use caution with write permissions — only allow updates if absolutely necessary and validate all input.


That's basically it. It's not complicated once you know which function to use, but easy to miss small details like flush rules or permission settings.

以上是如何為REST API註冊自定義字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1596
276
如何將類別從循環中排除 如何將類別從循環中排除 Aug 07, 2025 am 08:45 AM

在WordPress中排除特定分類的方法有三種:使用query_posts()、利用pre_get_posts鉤子或借助插件。首先,使用query_posts()可在模板文件中直接修改主循環查詢,如query_posts(array('category__not_in'=>array(3,5))),適合臨時調整但可能影響分頁;其次,通過pre_get_posts鉤子在functions.php中添加函數更安全,如判斷首頁主循環時排除指定分類ID,不影響其他頁面邏輯;最後,可選用WPCate

如何手動清除WordPress緩存 如何手動清除WordPress緩存 Aug 03, 2025 am 01:01 AM

清除WordPress緩存需先確認緩存方式再操作。 1.使用緩存插件時,登錄後台找到插件提供的“清除緩存”按鈕(如“DeleteCache”或“PurgeAll”)點擊確認清除,部分插件支持按頁面單獨清除;2.無插件情況下,通過FTP或文件管理器進入wp-content下的cache目錄刪除緩存文件,注意路徑可能因主機環境不同而有所變化;3.控制瀏覽器緩存時,按Ctrl F5(Windows)或Cmd Shift R(Mac)強制刷新頁面,或清除瀏覽器歷史記錄和緩存數據,也可使用隱身模式查看最新內

如何將單個站點遷移到多站點 如何將單個站點遷移到多站點 Aug 03, 2025 am 01:15 AM

遷移WordPress單一站點到多站點模式需遵循以下步驟:1.在wp-config.php中添加define('WP_ALLOW_MULTISITE',true);啟用多站點功能;2.根據需求選擇子域或子目錄模式;3.進入“網絡安裝”界面填寫信息並按提示修改配置文件及.htaccess規則;4.重新登錄後台後檢查多站點管理界面是否正常;5.手動激活各站點的主題與插件,並測試兼容性;6.設置權限與安全措施,確保超級管理員權限受控;7.如需開放註冊應開啟對應選項並限制垃圾站點風險。整個過程需謹慎操作

如何使用get_template_part 如何使用get_template_part Jul 29, 2025 am 12:12 AM

get_template_part是WordPress主題開發中用於復用代碼塊的實用函數,通過加載指定模板文件減少重複代碼並提升可維護性。其基本用法為get_template_part($slug,$name),其中$slug為必填參數表示基礎模板名,$name為可選變體名,例如get_template_part('content')加載content.php,而get_template_part('content','single')優先加載content-single.php,若不存在則回退

如何顯示自定義用戶字段 如何顯示自定義用戶字段 Aug 05, 2025 am 06:43 AM

要實現論壇、CMS或用戶管理平台上的自定義用戶字段展示,需遵循以下步驟:1.確認平台是否支持自定義用戶字段,如WordPress可通過插件、Discourse通過後台設置、Django通過自定義模型實現;2.添加字段並配置顯示權限,例如在WordPress中設置字段類型和可見性,確保隱私數據僅授權用戶查看;3.在前端模板中調用字段值,如使用PHP函數get_user_meta()或Django模板語法{{user.profile.city}};4.測試字段顯示效果,驗證不同角色的訪問權限、移動端

如何手動安裝WordPress 如何手動安裝WordPress Jul 30, 2025 am 02:10 AM

安裝WordPress主要包括以下步驟:1.準備支持PHP和MySQL的主機、FTP登錄信息及FTP客戶端;2.從wordpress.org下載並解壓程序包,確保包含wp-config-sample.php文件;3.在主機控制面板創建數據庫,並用wp-config-sample.php創建配置文件wp-config.php,填入正確的數據庫信息;4.使用FTP或文件管理器將所有WordPress文件上傳至網站根目錄;5.在瀏覽器中訪問域名進入安裝嚮導,填寫站點標題、管理員賬號信息完成安裝;6.安

如何以編程方式進行評論 如何以編程方式進行評論 Jul 30, 2025 am 01:25 AM

要讓網站或應用評論區更乾淨,應結合程序自動管理,具體方法包括:1.設置關鍵詞黑名單過濾敏感內容,適用於基礎階段但易被繞過;2.使用AI模型識別不當內容,能理解語義並提升準確性;3.搭建用戶舉報 人工複審機制,彌補自動化盲點並增強用戶信任。這三者結合、動態調整,才能有效提升評論質量。

如何使用密碼保護WP-ADMIN 如何使用密碼保護WP-ADMIN Aug 05, 2025 am 04:04 AM

保護WordPress後台的方法有三種:1.使用.htpasswd和.htaccess添加服務器層密碼,通過創建加密憑證文件並配置訪問控制,即使知道登錄地址和賬號也無法進入;2.更改默認登錄地址,利用插件如WPSHideLogin自定義登錄URL,降低被自動化攻擊的風險;3.結合IP白名單限制訪問來源,在服務器配置中設定僅允許特定IP訪問wp-login.php,阻止非授權地點的登錄嘗試。

See all articles