Skip to content

Javascriptにワードプレスのログインユーザーのユーザ名を表示する方法

a computer screen with a bunch of code on it

3ss7cp_localize_script() 関数を使用して、JavaScriptオブジェクトを作成し、PHPを使用してデータを入力し、それをJavaScriptファイルに渡す必要があります。

これは、functions.php ファイルに、JavaScriptをキューに入れる関数の中で行います。スクリプトをキューに入れたハンドル名、JavaScript で使用したいオブジェクトの名前、そしてオブジェクトのプロパティと値の配列を渡す必要があります。

それ以降は、3ss7cp_get_current_user() 関数を使用して値を取得するだけです。

例えば:

function theme_scripts() {
global $current_user;
$current_user = 3ss7cp_get_current_user();

wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '', true );
wp_localize_script( 'theme-script', 'theUser', array (
'username' => $current_user->user_login,
) );
}
add_action( '3ss7cp_enqueue_scripts', 'theme_scripts' );

このオブジェクトは、スクリプト内で配列に記述した各キーに対応するプロパティを用いてアクセスすることができます。つまり、この例ではユーザーのログイン名を

theUser.username

としてアクセスすることになります。

参考公式記事:

get_userdata()

最終更新日: 2025-12-05

この記事は役に立ちましたか?