WordPress のユーザープロフィール画面では、ソーシャルサービスの値を設定することができますが、デフォルトのサービスの中には、AIM や Yahoo!IM といった無関係なものもあり、さらに Twitter や Facebook のフィールドもありません。 これでは、デフォルトのフォームに手を加える必要があることがわかります。 WordPressには、プロフィールフィールドを追加・削除する方法が用意されています。 その方法をご紹介しましょう。
フィルターの設定
最初のステップでは、functions.phpファイルにプロフィールのキーと値の配列を受け取る関数を作成します。
1 2 3 4 5 6 |
function modify_contact_methods($profile_fields) { // Field addition and removal will be done here } add_filter('user_contactmethods', 'modify_contact_methods'); |
この関数は、保護された重要な配列へのアクセスを提供します。 返された値は、ユーザープロファイルフィールドのリストになります。
プロフィールフィールドの追加
新しいフィールド、例えばTwitterのハンドルを追加するには、渡された配列にキーを追加し、フィールドのラベルとして機能する値を追加します。
1 2 3 4 5 6 7 8 9 10 |
function modify_contact_methods($profile_fields) { // Add new fields $profile_fields['twitter'] = 'Twitter Username'; $profile_fields['facebook'] = 'Facebook URL'; $profile_fields['gplus'] = 'Google+ URL'; return $profile_fields; } add_filter('user_contactmethods', 'modify_contact_methods'); |
配列にそのキーと値を追加するだけで、フォームに新しいフィールドが追加されます。
プロファイルフィールドの削除
逆に、配列からキーを削除すると、ユーザープロファイルのフォームからフィールドが削除されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function modify_contact_methods($profile_fields) { // Add new fields $profile_fields['twitter'] = 'Twitter Username'; $profile_fields['facebook'] = 'Facebook URL'; $profile_fields['gplus'] = 'Google+ URL'; // Remove old fields unset($profile_fields['aim']); return $profile_fields; } add_filter('user_contactmethods', 'modify_contact_methods'); |
上記のコードでは、プロフィール編集フォームからAIMフィールドを削除しています。
カスタムフィールドの値の取得
カスタムフィールドの値を取得するには、get_the_author_metaメソッドを使用します。
1 2 |
// Retrieve a custom field value $twitterHandle = get_the_author_meta('twitter'); |
プロフィールフォームのフィールドを簡単に追加できる機能は素晴らしいです。プラグインを使わなくても、とても簡単にできます。