LoginSignup
4
2

More than 5 years have passed since last update.

WordPressの投稿中の一番最初の画像のURLを取得する

Posted at

忘備録。
アイキャッチ画像等が指定されない投稿でも、サムネイルとして画像を使いたい場合等に、投稿内にでてくる一番最初の画像で代替してしまおうという時に使うためのもの。


// 投稿内に出てくる一番最初の画像を取得する
function catch_post_image() {
    global $post;
    $first_img = '';
    preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

    if (isset($matches[1])) {
        $first_img = $matches[1][0];
    }

    if(empty($first_img)){
        $first_img = '';
    }

    return $first_img;
}

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