RSSフィードを使ってWordPress同士のコンテンツを共有

広告WordPress・PHP を学べる本

Amazonのアソシエイトとして、WordPress functions.phpは適格販売により収入を得ています。

概要説明

WordPress標準機能のRSSフィードを使って別のWordPressの投稿情報を取得・表示させるカスタマイズ。標準では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)) //任意のサイズ指定
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] で呼び出して任意の場所で表示ができます

関連機能

  1. WordPress で Google の検索から来た人だけに文を出すショートコード:リファラーと Cookie で見分ける

  2. WordPress予約フォームをSelectTypeで作成してページに埋め込む ( 無料版でお試し )

  3. WordPress の body タグに class を足す(トップページだけ・ページごとに変える方法)

サイドバー

よく使うカスタマイズ

最近の記事

Profile

PAGE TOP