LoginSignup
4
3

More than 5 years have passed since last update.

WordPressでimgタグを簡単に挿入する

Posted at

TL;DR

自分でビューヘルパーを作るとimgタグを書きやすく、見やすく生成出来るよ。

imgタグをお手軽に挿入したい

WordPressをやっていっている時に、沢山あるimgタグをベタ書きするなんてやってられませんよね。
こういう時、ビューヘルパーなんかを使って書きやすく、また見やすくするのは当然でしょう。

WordPress上にメディアとしてアップロードされたものは、get_image_tag();で簡単に呼び出せますが、記事の画像ではなくサイトの見た目にかかわる画像なども、関数で簡単に呼び出せるようにしておくと良いでしょう。

functions.php
/**
 * イメージタグの生成.
 *
 * @param $file_name
 * @param string $class
 * @param string $alt
 * @param integer $width
 * @param integer $height
 * @return null echo img tag
 */
function the_image($file_name, $class = '', $alt = '', $width = NULL, $height = NULL) {
  $extra_attr = '';

  if ($class) {
    $extra_attr .= ' class="' . esc_attr($class) . '"';
  }
  if ($width) {
    $extra_attr .= ' width="' . esc_attr($width) . '"';
  }
  if ($height) {
    $extra_attr .= ' height="' . esc_attr($height) . '"';
  }
  if ($alt) {
    $extra_attr .= ' alt="' . esc_attr($alt) . '"';
  }

  echo '<img src="' . get_theme_file_uri('/assets/images/' . $file_name) . '" ' . $extra_attr . ' >';
}

このような関数を用意しておくと、imgタグを簡単に生成することが可能になります。

functions.php
<?php the_image('my_pic.png', 'profile', 'プロフィール画像', 500, 500); ?>

関数にしておくとIDEで引数の説明が出たりするのもいいですね。get_theme_file_uri('assets/images/*'); のような、地味に書くのが手間な定型句を書かずに済むのもお得です。

このように少し面倒くさいな、と感じるところはガンガンビューヘルパーを作っていくと良いと思います💪

4
3
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
4
3