钩子文档

personal_options_update

💡 云策文档标注

概述

personal_options_update 是一个 WordPress 动作钩子,在用户编辑自己的个人资料页面加载前触发,主要用于保存添加到个人资料页的自定义字段。

关键要点

  • 该钩子仅在当前用户编辑自己的个人资料时触发,不适用于其他用户的资料页。
  • 参数为 $user_id(整数类型),表示用户 ID。
  • 若需在所有个人资料页(包括其他用户的)应用钩子,需同时使用 edit_user_profile_update 钩子。
  • 钩子源为 do_action( 'personal_options_update', $user_id ),自 WordPress 2.0.0 版本引入。

代码示例

add_action('personal_options_update', 'update_extra_profile_fields');

function update_extra_profile_fields( $user_id ) {
    if ( current_user_can( 'edit_user', $user_id) ) {
        update_user_meta( $user_id, 'my_custom_field', sanitize_text_field( $_POST['your_field'] ) );
    }
}

注意事项

在保存自定义字段时,应使用 current_user_can( 'edit_user', $user_id ) 检查权限,并考虑数据安全,如使用 sanitize_text_field 进行清理。


📄 原文内容

Fires before the page loads on the ‘Profile’ editing screen.

Description

The action only fires if the current user is editing their own profile.

Parameters

$user_idint
The user ID.

More Information

Generally, action hook is used to save custom fields that have been added to the WordPress profile page.

This hook only triggers when a user is viewing their own profile page. If you want to apply your hook to ALL profile pages (including users other than the current one), then you also need to use the edit_user_profile_update hook.

Source

do_action( 'personal_options_update', $user_id );

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    This example shows how to save a custom field named ‘your_field’…

    add_action('personal_options_update', 'update_extra_profile_fields');
     
    function update_extra_profile_fields( $user_id ) {
        if ( current_user_can( 'edit_user', $user_id) ) {
            update_user_meta( $user_id, 'my_custom_field', sanitize_text_field( $_POST['your_field'] ) );
        }
    }

  2. Skip to note 4 content

    (From Codex)
    This example shows how to save a custom field named ‘your_field’…

    add_action( 'personal_options_update', 'wporg_update_extra_profile_fields' );
     
     function wporg_update_extra_profile_fields( $user_id ) {
         if ( current_user_can( 'edit_user', $user_id ) )
             update_user_meta( $user_id, 'my_custom_field', $_POST['your_field'] );
     }