ACF非常适合管理用户自定义字段,但使用update_user_meta()
保存自定义数据,然后使用$user->get( \'whatever\' );
下面是一个让用户设置和更新推特句柄的表单示例:
<?php
// Grab the current user (Or redirect to login page)
$user = wp_get_current_user();
if ( !$user->exists() ) {
wp_safe_redirect(wp_login_url(home_url($_SERVER[\'REQUEST_URI\'])));
exit;
}
// Check if form was submitted
if ( isset($_POST[\'submitted\']) ) {
// Verify nonce
if ( !isset($_POST[\'_wpnonce\']) || !wp_verify_nonce( $_POST[\'_wpnonce\'], \'user_form\' ) ) {
wp_die("Invalid nonce.");
}
update_user_meta( $user->ID, \'twitter_handle\', $_POST[\'twitter_handle\'] );
// Do a PGP redirect to prevent submitting the same for data multiple times.
// Read more about PGP here: https://en.wikipedia.org/wiki/Post/Redirect/Get
wp_safe_redirect( add_query_arg( \'updated\', \'\', home_url($_POST[\'_wp_http_referer\']) ) );
exit;
}
get_header();
?>
<?php if ( isset($_GET[\'updated\']) ) : ?>
<p>Your twitter handle has been updated!</p>
<?php endif; ?>
<form method="POST">
<label for="twitter_handle">Twitter Handle</label>
<input type="text" id="twitter_handle" name="twitter_handle" value="<?php echo esc_attr($user->get("twitter_handle")); ?>">
<?php wp_nonce_field("user_form"); ?>
<input type="hidden" name="submitted" value="1">
<button type="submit">Save changes</button>
</form>
<?php get_footer(); ?>