Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created September 4, 2020 06:29
Show Gist options
  • Select an option

  • Save maheshwaghmare/bf4dc344348646c5ecb20e178b053776 to your computer and use it in GitHub Desktop.

Select an option

Save maheshwaghmare/bf4dc344348646c5ecb20e178b053776 to your computer and use it in GitHub Desktop.
Show WordPress RSS Feed with Shortcode. E.g. [show_rss_feed url="https://maheshwaghmare.com/feed/"]
<?php
/**
* Show RSS feed with Shortcode.
*
* @example [show_rss_feed url="https://maheshwaghmare.com/feed/"]
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*/
if( ! function_exists( 'prefix_show_rss_feed' ) ) :
function prefix_show_rss_feed( $atts, $content ) {
$atts = shortcode_atts( array(
'url' => ''
), $atts );
// Missing URL.
if( empty( $atts['url'] ) ) {
return 'ERROR: Feed URL is missing.';
}
// Fetch RSS feeds.
$rss = fetch_feed( $atts['url'] );
// Fetching error.
if ( is_wp_error( $rss ) ) {
return 'ERROR: ' . $rss->get_error_message();
}
// Quantity error.
if ( ! $rss->get_item_quantity() ) {
$rss->__destruct();
unset( $rss );
return '<ul><li>An error has occurred, which probably means the feed is down. Try again later.</li></ul>';
}
// Return feed list.
$output = '<ul>';
foreach ( $rss->get_items() as $item ) {
$link = $item->get_link();
$link = esc_url( strip_tags( $link ) );
$title = esc_html( trim( strip_tags( $item->get_title() ) ) );
if ( empty( $title ) ) {
$title = 'Untitled';
}
if ( '' === $link ) {
$output .= "<li>$title</li>";
} else {
$output .= "<li><a href='$link'>$title</a></li>";
}
}
$output .= '</ul>';
$rss->__destruct();
unset( $rss );
return $output;
}
add_shortcode( 'show_rss_feed', 'prefix_show_rss_feed' );
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment