【WordPress開発】記事の最初の画像を取得方法

サムネイル設定していないときに、最初の画像をサムネイルとして扱いたくてやりました。

WordPressで記事の最初の画像を取得

/**
 * 記事の最初の画像を取得
 *
 * @param int|null $id
 * @return string
 */
function get_first_image($id = null): string
{
  $post = get_post($id);
  preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = isset($matches[1][0]) ? $matches[1][0] : '';
  return $first_img;
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です