WP 投稿IDからサムネイルを取得する関数

functions.php

/**
 * 投稿IDからアイキャッチ画像のURLを取得
 */
//no-img取得
define("DIRE", get_template_directory_uri());   //テンプレートディレクトリまでのURL
define("NOIMG", DIRE . "/img/no_img.png");  //NoImage画像のURL

//関数定義
function get_thumb_url($size = 'full', $post_id = null)
{
    $post_id = ($post_id) ? $post_id : get_the_ID();

    if (!has_post_thumbnail($post_id)) return NOIMG;

    $thumb_id = get_post_thumbnail_id($post_id);
    $thumb_img = wp_get_attachment_image_src($thumb_id, $size);
    $thumb_src = $thumb_img[0];

    return $thumb_src;
}

この関数を使いたい箇所で下記のように記述

<?php

$post_id = get_field('rank_1')->ID; //これはカスタムフィールドの場合

echo '<img src="' . get_thumb_url($post_id) . '" alt="">';
?>

参考にしたのは下記です!感謝です!

wemo.tech