概要説明
WordPress標準機能のRSSフィードを使って別のWordPressの投稿情報を取得・表示させるカスタマイズ。標準ではRSSフィードにアイキャッチ画像(サムネイル)が無いため追加方法も合わせて掲載しています。ポータルサイトなどでご活用ください。
標準のRSSにサムネイル画像(アイキャッチの情報を追加)
functions.php
/*----------------------------------------------------
RSSフィードにアイキャッチ画像を追加
----------------------------------------------------*/
if ( !function_exists( 'rss_add_thumbnail' ) ){
function rss_add_thumbnail($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = get_the_post_thumbnail($post->ID) . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'rss_add_thumbnail');
add_filter('the_content_feed', 'rss_add_thumbnail');
}
こちらはRSSの配信側に設定。サムネイル画像を使用しない場合は上記対応は不要です。
RSSフィードに追加する画像のサイズ指定
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,'full') //フルサイズ get_the_post_thumbnail($post->ID, array(150,150)) //任意のサイズ指定
RSSフィードのデータを受け取って表示させる
functions.php
/*----------------------------------------------------
RSSフィードの情報を取得しショートコードで呼び出す
----------------------------------------------------*/
if ( ! function_exists( 'shortcode_rss' ) ) {
function shortcode_rss() {
$url = 'https://xxxxxxx/feed/';
$count = 3;
$feed = fetch_feed( $url );
if ( is_wp_error( $feed ) ) {
return '';
}
$rss_items = $feed->get_items( 0, $feed->get_item_quantity( $count ) );
$rss_html = '';
foreach ( $rss_items as $item ) {
$link = esc_url( $item->get_permalink() );
$date = esc_html( $item->get_date( 'Y年n月j日' ) );
$title = esc_html( $item->get_title() );
$content = esc_html( mb_strimwidth( wp_strip_all_tags( $item->get_content() ), 0, 200, '...', 'UTF-8' ) );
// 本文の最初の画像をサムネイルにする
$site_img = '';
if ( preg_match( '/<img[^>]+src=(["\'])(.+?)\1/i', $item->get_content(), $img ) ) {
$site_img = '<img src="' . esc_url( $img[2] ) . '" alt="" loading="lazy">';
}
$rss_html .= '<div class="feed_item">' . $site_img
. '<a href="' . $link . '" rel="nofollow"><h2>' . $date . ' : ' . $title . '</h2></a>'
. '<p>' . $content . '</p></div>';
}
return $rss_html; // ショートコードは echo ではなく return で返す
}
add_shortcode( 'rss', 'shortcode_rss' );
}
以前のコードは、add_shortcode の関数名に引用符がなく、PHP 8 ではエラーで画面が出なくなる状態でした。あわせて、フィードが読めないときの処理・画像の URL のエスケープ・ショートコードを return で返す形に直しました(2026/10/18・作業環境で動きを確かめています)。
[rss] で呼び出して任意の場所で表示ができます


