ショウジンブログ on Hatena

“お芝居をしないと、この社会では異邦人として扱われるほかない”

Feed(RSS等)にアイキャッチ画像を含んで配信する@WordPress

最近、あまりRSSがどうのということも言われなくなり(RSS Readerのサービス、アプリも閉鎖したりで縮小傾向にあるような)、そもそもFeedを積極的に購読している利用者も少なくなってきているかもしれませんが、私はグイグイ利用しているので一応メモしておきます。

WordPressのデフォルト状態ではRSS等のFeedにアイキャッチ画像は含まれません。

Feedにもアイキャッチを含める場合には以下の記述を使用しているテーマのfunctions.phpに追加します。

<?php
// Feedにアイキャッチ画像を表示する
function post_thumbnail_feeds($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content;
    }
    return $content;
}
add_filter('the_excerpt_rss', 'post_thumbnail_feeds');
add_filter('the_content_feed', 'post_thumbnail_feeds');

これでWordPressサイトで生成されるFeedにアイキャッチ画像の情報も含まれるので(descriptionに)、たとえば別のサイトでアイキャッチ画像つきで投稿を表示したい場合、タイトル、抜粋文、アイキャッチ画像を表示することが出来ます。

blog.showzine.co

Feedに含むアイキャッチ画像のサイズですが、以下のように設定出来るようです。前述のコードの6行目の「get_the_post_thumbnail」の引数を変更します。

// サムネイルサイズでアイキャッチ画像を表示
get_the_post_thumbnail($post->ID, 'thumbnail')

// 中サイズでアイキャッチ画像を表示
get_the_post_thumbnail($post->ID, 'medium')

// 大サイズでアイキャッチ画像を表示
get_the_post_thumbnail($post->ID, 'large')

// フルサイズでアイキャッチ画像を表示
get_the_post_thumbnail($post->ID, 'large')

// 指定サイズでアイキャッチ画像を表示(縦横比は保たれる)
get_the_post_thumbnail($post->ID, array(150,150))

本格ビジネスサイトを作りながら学ぶ WordPressの教科書 Ver.4.x対応版

本格ビジネスサイトを作りながら学ぶ WordPressの教科書 Ver.4.x対応版