複数人でブログを運営している時に便利!WordPressにて著者毎に表示を変えるための条件分岐

複数人でブログを運営している時に便利!WordPressにて著者毎に表示を変えるための条件分岐

複数人でブログを運営している時に便利!WordPressにて著者毎に表示を変えるための条件分岐

著者別アーカイブページなどで、各著者毎に別の画像を表示したりと、見た目を変えたい時の条件分岐についてです。

クライアントワークにて、著者別アーカイブページで、それぞれのユーザーに異なる画像を設置したいという要望をいただきました。その時の実装メモになります。

スポンサードリンク

WordPressで著者毎に表示を変えるための条件分岐

著者毎に表示を切り替えるには、以下のようにswitchを使って、ユーザーID毎に条件分岐させます。

<?php
  switch (get_the_author_ID()) {
  case 1: 
  print '<div class="authors-img"><img src="' .get_template_directory_uri(). '/images/author/author1.jpg"></div>';
  break;

  case 2: 
  print '<div class="authors-img"><img src="' .get_template_directory_uri(). '/images/author/author2.jpg"></div>';
  break;

  case 3: 
  print '<div class="authors-img"><img src="' .get_template_directory_uri(). '/images/author/author3.jpg"></div>';
  break;

  default:
  break;
} ?>

今回実装したのはauthor.phpで、著者のアーカイブページに固有の画像を表示させました。上記ではテーマフォルダ配下の/images/author/author○.jpgが表示されます。

get_the_author_ID関数で著者のIDを取得しています。caseでユーザーIDを指定し、それぞれ異なる画像を表示するようにしています。

上記は画像を表示した例ですが、処理については適宜ご変更ください。

正常に条件分岐されない場合

もしも上述した方法でうまく動かない場合は、is_authorで条件分岐させてみてください。


<?php if ( is_author('1')): ?>
  <div class="authors-img"><img src="<?php echo get_template_directory_uri(); ?>/images/author/author1.jpg"></div>
<?php elseif ( is_author('2')): ?>
  <div class="authors-img"><img src="<?php echo get_template_directory_uri(); ?>/images/author/author2.jpg"></div>
<?php elseif ( is_author('3')): ?>
  <div class="authors-img"><img src="<?php echo get_template_directory_uri(); ?>/images/author/author3.jpg"></div>
<?php else: ?>
  <div class="authors-img"><img src="<?php echo get_template_directory_uri(); ?>/images/author/author-etc.jpg"></div>
<?php endif; ?>

is_authorの数字部分にユーザーIDを指定します。

前にget_the_author_IDでちゃんとユーザーIDを取得できないことがあって、is_authorで条件分岐させたら正常に表示を切り替えることができました。

ユーザー数が多くて半自動化したい場合

ユーザーの数が多くて、いちいち一人ずつ条件分岐させるのが面倒な場合は、以下のように半自動化することもできます。


<?php
$author_jpg_check = get_stylesheet_directory().'/images/author/author'.$author.'.jpg';
$author_png_check = get_stylesheet_directory().'/images/author/author'.$author.'.png';
$author_jpg = get_stylesheet_directory_uri().'/images/author/author'.$author.'.jpg';
$author_png = get_stylesheet_directory_uri().'/images/author/author'.$author.'.png';
if(file_exists($author_jpg_check)){
  echo '<div class="authors-img"><img src="'.$author_jpg.'"></div>';
} elseif(file_exists($author_png_check)) {
  echo '<div class="authors-img"><img src="'.$author_png.'"></div>';
} else {}
?>

authorディレクトリの中にauthor〇〇.jpgもしくはauthor〇〇.pngがあるかどうかをチェックして、ある場合は表示しています。

あとがき

複数人で運営しているブログで、著者別アーカイブページを作り込みたい時に活用できるかと思います。あとは、記事ページで著者毎に表示を切り替えるのも良いですね。

複数人でブログを運営している場合は、ぜひ参考にしていただければと思います。

この記事が気に入ったら
いいね!してね♪

Twitter で
スポンサードリンク

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です