1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アイキャッチの画像URLだけを取得する関数

Last updated at Posted at 2018-04-21

訂正:
すみません、既に関数ありました。@just_a_personさんありがとうございます。

get_the_post_thumbnail_url

function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
    $post_thumbnail_id = get_post_thumbnail_id( $post );
    if ( ! $post_thumbnail_id ) {
        return false;
    }
    return wp_get_attachment_image_url( $post_thumbnail_id, $size );
}

WordPressでアイキャッチ画像を表示する時は、
the_post_thumbnail()
が有名ですが、画像のURLだけを欲しい事がよくあります。
なので関数にまとめておくと便利です。

functions.php
/**
* 投稿のアイキャッチ画像を取得して、画像urlを返す
*
*
* @param type int $post_id
* @param type string $size
* @return string image_src_url
*/
function return_eyecatch_src($post_id,$size='medium')
{
    $post_thumbnail_id = get_post_thumbnail_id($post_id);
    $thumb_src = wp_get_attachment_image_src($post_thumbnail_id,$size);
    if($thumb_src !== false){
        return $thumb_src[0];
    }else{
        return false;
    }
}

$post->IDを渡して、第二引数にサイズを渡します。
使い方はループ内で、

$thumb_src = return_eyecatch_src($post=>ID);
$thumb_output = '';
if($thumb_src){
  $thumb_output = '<img src="'.$thumb_src.'" alt="">';
}

のような感じです。

wp_get_atachement_img_src()

はサイズなどの情報が取れて便利ですが、
画像URLだけを使う場合が大半なので、関数でまとめた方が楽かもです。

1
2
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?