【WordPress】アイキャッチ画像のURLを取得する方法

アイキャッチ画像を投稿記事の中でも使いたい場合、<img>でURLを入れても良いのですが、ショートコードを作って使う方法をご紹介します。

ショートコードを作る(カスタムショートコード)

functions.php

PHP
function get_featured_image_url_shortcode() {
    if (has_post_thumbnail()) {
        return get_the_post_thumbnail_url(get_the_ID(), 'full');
    }
    return '';
}
add_shortcode('featured_image_url', 'get_featured_image_url_shortcode');

投稿の中

PHP
<?img src="[ featured_image_url ]" alt="">
※全角スペース入れています。

これで、投稿に設定されたアイキャッチ画像のURLが <img src=””> に自動で挿入されます。

では、alt=””は?
alt=””もメディアの画像の「代替テキスト」の箇所を自動挿入したい場合もご紹介します。

ショートコードを作る(カスタムショートコード)

functions.php

PHP
function shortcode_featured_image() {
    if (has_post_thumbnail()) {
        $thumb_id  = get_post_thumbnail_id(get_the_ID());
        $thumb_url = wp_get_attachment_image_url($thumb_id, 'full');
        $thumb_alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);

        return '<img src="' . esc_url($thumb_url) . '" alt="' . esc_attr($thumb_alt) . '">';
    }
    return '';
}
add_shortcode('featured_image', 'shortcode_featured_image');

投稿の中

PHP
[featured_image]

これで、
<img src=”https://example.com/wp-content/uploads/xxxx.jpg” alt=”メディアで設定した代替テキスト”>
という形で出力されます。

いかがでしょうか。
投稿する際に毎回メディアからURLをコピペしなくても、ショートコードで自動で出力してくれるとラクですよね。

他にもあるよ。関連記事

皆様の意見を送ってください。

ご意見・ご感想

人気記事

人気記事

最新記事

ブログカテゴリー

タグ

プロフィール

プロフィール画像

猫田 ねこ

パチンコ店勤務からweb制作会社へ転職という異色の経歴。漫画大好き。アニメ大好き。パチンコ大好きな、ねこです。

利用規約  お問い合わせ

ページトップへ