Display an External RSS Feed With a Shortcode
Adds an [rss_feed] shortcode that shows the latest items from any RSS or Atom feed, such as your podcast, YouTube channel or a partner blog, on a page.
Opens WPIDE on
Code
add_shortcode( 'rss_feed', function ( $atts ) {
$atts = shortcode_atts( array(
'url' => '',
'items' => 5,
'show_date' => 'yes',
'show_summary' => 'no',
), $atts, 'rss_feed' );
$url = esc_url_raw( $atts['url'] );
if ( ! $url ) {
return '';
}
include_once ABSPATH . WPINC . '/feed.php';
$feed = fetch_feed( $url );
if ( is_wp_error( $feed ) ) {
return current_user_can( 'edit_posts' ) ? '<p class="wpide-rss-error">Feed could not be loaded: ' . esc_html( $feed->get_error_message() ) . '</p>' : '';
}
$items = $feed->get_items( 0, min( 20, max( 1, absint( $atts['items'] ) ) ) );
if ( ! $items ) {
return '';
}
$html = '<ul class="wpide-rss-feed">';
foreach ( $items as $item ) {
$html .= '<li><a href="' . esc_url( $item->get_permalink() ) . '" rel="noopener">' . esc_html( wp_strip_all_tags( (string) $item->get_title() ) ) . '</a>';
if ( 'yes' === $atts['show_date'] && $item->get_date( 'U' ) ) {
$html .= ' <time datetime="' . esc_attr( gmdate( 'c', (int) $item->get_date( 'U' ) ) ) . '">' . esc_html( wp_date( get_option( 'date_format' ), (int) $item->get_date( 'U' ) ) ) . '</time>';
}
if ( 'yes' === $atts['show_summary'] ) {
$html .= '<p>' . esc_html( wp_trim_words( wp_strip_all_tags( (string) $item->get_description() ), 30 ) ) . '</p>';
}
$html .= '</li>';
}
return $html . '</ul>';
} );
Notes
Example: [rss_feed url="https://example.com/feed/" items="5" show_date="yes" show_summary="no"]. Feeds are cached for 12 hours by WordPress.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.