WordPressのfetch feed関数でRSSを取得しました。忘れないうちにメモ。
表示させたいとこへ以下。
※下記のコードは、ACFのリピーターフィールドを指定してるけど、$rss_feedにURLを指定すればよい。
<?php while(the_repeater_field('rss_feed')): $rss_feed[] = get_sub_field('rss_url'); endwhile; rss_prog($rss_feed);?>
Functions.phpに以下。htmlの部分は適当に修正する。preg_matchで画像を見つけてサムネイルにしてる。
<?php //RSS表示 function rss_prog($rss_feed){ include_once( ABSPATH . WPINC . '/feed.php' ); $rss = fetch_feed($rss_feed); $maxitems = 0; if ( ! is_wp_error( $rss ) ) : // ちゃんとフィードが生成されているかをチェックします。 $maxitems = $rss->get_item_quantity( 5 ); $rss_items = $rss->get_items( 0, $maxitems ); endif; ?> <ul class="news-list"> <?php if ( $maxitems == 0 ) : ?> <li>記事がありません</li> <?php else : ?> <?php // Loop through each feed item and display each item as a hyperlink. ?> <?php foreach ( $rss_items as $key => $item) : $first_img = ''; if ( preg_match( '/<img.+?src=[\'"]([^\'"]+?)[\'"].*?>/msi', $item->get_content(), $matches ) ) { $first_img = $matches[1]; }?> <li><div class="news-img c-col5"> <?php if (!$first_img) : ?> <img src="<?php echo get_template_directory_uri(); ?>/image/noimage.png"> <?php else : ?> <img src="<?php if($first_img) : echo esc_html( $first_img ); else: "";endif; ?>" width="100" height="60"> <?php endif; ?></div><div class="news-text c-col6"> <p class="n-tit"><a href="<?php echo esc_url( $item->get_permalink() ); ?>" title="<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->get_date('j F Y | g:i a') ); ?>"> <?php echo esc_html( $item->get_title() ); ?></a></p> <p class="n-info"><?php echo $item->get_feed()->get_title(); // サイト名 ?><?php echo $item->get_date('j F Y | g:i a'); // サイト名 ?></p> </div></li> <?php endforeach; ?> <?php endif; ?> </ul> <?php }
関数リファレンス/fetch feed
https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/fetch_feed