コーディング

投稿した記事内の最初の画像を取得する方法|WordPress

投稿した記事内の最初の画像を取得する方法|WordPress

WordPressのテーマを作成している時に少しだけ引っかかった部分を、備忘録として残しておきたいと思います。

投稿された記事内の最初の画像を取得する方法です。

取得した画像をサムネイルに使用したい時などに使えます。

functions.php

functions.phpに以下のコードを記述します。

function first_post_image(){
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('//i', $post->post_content, $matches);
    $first_img = $matches[0];
 
    if(empty($first_img)){
        $first_img = get_template_directory_uri()."/common/img/base/ogimage.png";
    }
    return $first_img;
}

出力する

画像を表示したいimgタグのsrc属性で以下を実行します。


参考

こちらの記事を参考にさせていただきました。
【WordPress】投稿の中の最初の画像を取得する方法