• HOME
  • Wordpress
  • [Wordpress]記事内の最初の画像を取得する方法

2020/06/30 20:43

[Wordpress]記事内の最初の画像を取得する方法

投稿記事内の1枚目の画像の取得方法を紹介します。

ランキングやオススメ記事の一覧の出力時、リンクに貼るサムネとかを「最初の画像」で指定したい時に有効です。

コピペで使えるので簡単です。

 

functions.phpに追記

 

まずは1枚目の画像を取得するアクションをfunctions.phpファイルに追記。

 

【functions.php】

function catch_that_image() {

  global $post, $posts;

  $first_img = '';

  ob_start();

  ob_end_clean();

  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

  $first_img = $matches [1] [0];

if(empty($first_img)){ //画像がなかった場合

    $first_img = "/images/noimages.jpg";

  }

  return $first_img;

}

 

 

ちなみに

$first_img = "/images/noimages.jpg";

の箇所は、画像がなかった場合のものですので、「NO IMAGES」的な画像を1枚用意しておくといいかと思います。

 

 

出力方法

 

後はループ内の下記のような感じで書けば出力可能です。

 

【php】

<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>">

 

alt箇所は適宜変更で。

簡単ですね!

 

現場から以上です!

 

1762

PICK UP