如何在挂钩 triggered/fired 时向自定义用户字段添加值

How to add value to a custom user field when an hook is triggered/fired

当挂钩 triggered/fired 时,我如何向用户配置文件中的自定义文本字段添加值。我已经能够使用以下代码添加一个名为 example 的自定义字段

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("Example Section", "blank"); ?></h3>

    <table class="form-table">
    <tr>
        <th><label for="example"><?php _e("Example"); ?></label></th>
        <td>
            <input type="text" name="example" id="example" value="<?php echo esc_attr( get_the_author_meta( 'example', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e("This field should add YES when to field when a hook is triggered ad empty if hook not triggered."); ?></span>
        </td>
    </tr>
    </table>
<?php }

并使用以下代码保存输入

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }
    update_user_meta( $user_id, 'example', $_POST['example'] );
}

我希望在触发 user_register 挂钩时用 YES 填充这个新生成的自定义字段(即,当用户注册时,YES 应该添加到该字段并更新)

这样我就可以获得 YES 值并使用它来动态显示内容。像

$user = wp_get_current_user();
if ( get_the_author_meta( 'example', $user->ID ) = 'YES') {
   //Show this page
} else {
   return 'Your are not allowed to view this page';
}

我怎样才能做到这一点?谢谢

这应该有效:

function add_yes_to_field ( $user_id ) {
    update_user_meta( $user_id, 'winner', 'YES' );
} 
add_action( 'user_register', 'add_yes_to_field');

关于get_the_author_meta(),我不认为你真的可以用它获取用户元数据,因为它调用get_userdata()。您可以改用 get_user_meta()

https://developer.wordpress.org/reference/functions/get_the_author_meta/