LoginSignup
1
2

More than 5 years have passed since last update.

WordPressで記事内に最初に使われている画像を取得する方法

Posted at

記事内で最初に使用されている画像の取得方法

記事の簡単な見出しを作ろうと思った時に記事で使用されている画像を使いたかったのでやり方メモ

  • 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/default.jpg"; // 記事に画像がなかった場合表示する
    }
    return $first_img;
}
  • 表示したい箇所に記載する内容
<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" />

これで無事に最初の画像が取得できました!

以上

1
2
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
2