1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressのユーザーに独自のフィールド項目を追加する方法

Last updated at Posted at 2019-04-30

やりたいこと

記事詳細ページ下部に「この記事を書いた人」のユーザー画像を表示したい。
まなびとサイトのキャプチャ

やり方

1. 管理画面のユーザー編集画面に画像URLを入れる項目を追加

画像の登録自体は、管理画面のメディア機能があるので、画像URLを入力できるようにする。

functions.phpに以下を追加

function xxxxxx_modify_user_contact_methods( $user_contact ) {

	$user_contact['blog_author_img_url']   = 'この記事を書いた人:画像URL';

	return $user_contact;
}
add_filter( 'user_contactmethods', 'xxxxxx_modify_user_contact_methods' );

blog_author_img_urlは自分で一意なIDをつける。
この記事を書いた人:画像URLはユーザー編集のラベル名。

これを行うとユーザー編集に項目が追加される。
ユーザー編集に項目が追加

2. 記事詳細ページに画像を表示

登録はできるようになったので、imgタグを表示する記述をsingle.phpに追加。


$author_img_url = get_the_author_meta( 'blog_author_img_url' );
if( !empty( $author_img_url ) ){
	echo '<img src="' . esc_url( $author_img_url ) . '" alt="' . esc_attr( get_the_author_meta( 'display_name' ) ) . '">';
}
  • get_the_author_meta()に、1.で自分で名前をつけたblog_author_img_urlを指定すると取得できる。
  • if( !empty( $author_img_url ) )で入力されているかチェック。
  • 表示するときに、esc_url()で脆弱性対策でエスケープかける。
  • 画像のaltはget_the_author_meta( 'display_name' )で「ブログ上の表示名」を取得。これもesc_attr()でエスケープかける。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?