Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.