更新情報をwordpressで表示する際、自分のサイトや、Wordpressサイトの更新情報なら表示は簡単ですが、wordpress以外のサイトの場合、RSSを使ったもの表示方法が便利です。
今回は、プラグインなしでRSSを読み込んで記事のカードを画像付きで表示させる方法についてご紹介します。
phpを任意の場所に表示させる方法
WordPressでRSSを使ってリスト表示させるにはPHPを使用します。
phpを任意の場所に記述して表示させるには下のリンクを参照ください。
出力したサンプル
実際にphpのコードを記述して表示させたサンプルは以下です。
出力は、SANGOのカードタイプCのPCでみた場合横長に出力されるタイプです。






RSSを表示させるphpのコード
以下のコードの3行目「$rss = fetch_feed(‘ http://rss_url_here/atom.xml‘ ); 」に表示させたいRSSフィードのURLを入力し、5行目で表示個数をします。
このコードはwordpressのSANGOの標準のCSSを適用させているので、それ以外のテーマの場合CSSを改修する必要があるのでご注意ください。
コードを表示する
<?php
include_once( ABSPATH . WPINC . '/feed.php' );
$rss = fetch_feed( 'https://dubdesign.net/feed/' ); // ここにURLを入力する
if ( !is_wp_error( $rss ) ) {
$maxitems = $rss->get_item_quantity( 6 );
$rss_items = $rss->get_items( 0, $maxitems );
}
?>
<?php if ( !empty( $maxitems ) ) : ?>
<?php if ($maxitems == 0) echo '<h2>該当する記事がありませんでした.</h2>';
else
foreach ( $rss_items as $item ) : ?>
<a class="c_linkto longc_linkto" href="<?php echo $item->get_permalink(); ?>" target="_blank">
<?php
$first_img = '';
if ( preg_match( '/<img.+?src=[\'"]([^\'"]+?)[\'"].*?>/msi',
$item->get_content(), $matches )
) { $first_img = $matches[1]; } ?>
<?php if ( !empty( $first_img ) ) : ?>
<span class="longc_img"><img width="520" height="300" src="<?php echo esc_attr( $first_img ); ?>" /></span><?php endif; ?>
<span class="longc_content c_linkto_text"><time class="pubdate sng-link-time dfont" itemprop="datePublished" datetime="<?php echo $item->get_date('Y.m.d');// 日付 ?>"><?php echo $item->get_date('Y.m.d');// 日付 ?></time><span class="longc_title"><?php echo $item->get_title();// タイトル ?></span></span></a>
<?php endforeach; ?>
<?php endif; ?>