<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/* https://weusewp.com/tutorial/change-author-url-slug-base/ */
function haup_user_profile_author_slug_panel_init( $user ){
$head_text = __( 'User Slug(Optional)','hima-art-utility' );
$value = $user->user_nicename;
$text = __( 'You can change the user name displayed in the URL of the authors post list etc. to any character string. Single-byte alphanumeric characters and "-" and "_" can be used','hima-art-utility');

/* nonceフィールドの設定 */
/* save_postのところでも同一のキーとフィールドを設定すること */
	$nonce_key = 'haup_change_user_slug_nonce_key';
	$nonce_field = '_haup_change_user_slug_nonce_field';

	wp_nonce_field( $nonce_key , $nonce_field );

echo '<div class="ha-admin-profile-pannel-wrapper">';
echo '<h2>'.esc_html($head_text).'</h2>';
echo '<p>'.esc_html($text).'</p>';
echo '<input type="text" name="user_nicename" id="user_nicename" value="'.esc_html($value).'" class="regular-text" />';
echo '</div>';

}
add_action( 'show_user_profile', 'haup_user_profile_author_slug_panel_init' );
add_action( 'edit_user_profile', 'haup_user_profile_author_slug_panel_init' );

/* user_nicenameを書き換える */
function haup_author_slug_profile_update( $errors, $update, $user ) {

/* nonceチェック（正しい場所から更新されているかのチェック） */
	$nonce_key = 'haup_change_user_slug_nonce_key';
	$nonce_field = '_haup_change_user_slug_nonce_field';

	//nonceフィールドがなければ無視する
	if ( !isset( $_POST[$nonce_field] ) ){
		return;
	}

	//nounceが正しくなければ無視する
	if ( !wp_verify_nonce( sanitize_text_field( wp_unslash($_POST[$nonce_field])), $nonce_key ) ){
		return ;
	}

	if ( !$update ) return;


	$user_login = '';
	$user_nicename = '';

	if(isset( $_POST['user_login'] )){
		$user_login = sanitize_text_field(wp_unslash($_POST['user_login']));
	}

	if(isset( $_POST['user_nicename'] )){
		$user_nicename = sanitize_text_field(wp_unslash($_POST['user_nicename']));
	}


	if ( empty( $_POST['user_nicename'] ) ) {
		$user->user_nicename = sanitize_text_field(wp_unslash($user_login));
	} else {
		$user->user_nicename = sanitize_text_field(wp_unslash($user_nicename));
	}
}
add_action( 'user_profile_update_errors', 'haup_author_slug_profile_update', 10, 3 );
