How to Display The Feed Content of a Website in WordPress

The fetch_feed is a built-in WordPress function that retrieves and parses an external feed.
Under-the-hood, it’s powered by SimplePie – a very fast and easy-to-use PHP feed parser.

Follow me as I walk us through the steps in using fetch_feed to display the feed content of this blog (w3guy.com).

  1. First, include the feed.php file at wp-includes folder.
    
    <?php
    include_once( ABSPATH . WPINC . '/feed.php' );
    
  2. Use the fetch_feed function to get a SimplePie feed object from the feed source.
    
    $rss = fetch_feed( 'https://w3guy.com/feed' );
    
  3. Halt execution if fetch_feed result to an error.
    
    if ( is_wp_error( $rss ) )
    return;
    
  4. Determine the total feed items, but limit it to a maximum of eight (8).
    
    $maxitems = $rss->get_item_quantity( 5 );
    
  5. Build an array of all the items, starting with first element (element 0).
    
    $rss_items = $rss->get_items( 0, $maxitems ); 
    
  6. If there is no feed item, output the text No feed item otherwise Loop through each feed item and display each item as a hyperlink.
    
    <ul>
    	<?php if ( $maxitems == 0 ) : ?>
    		<li><?php echo 'No feed item'; ?></li>
    	<?php else : ?>
    		<?php foreach ( $rss_items as $item ) : ?>
    			<li>
    				<a href="<?php echo esc_url( $item->get_permalink() ); ?>"
    				   title="<?php printf( 'Posted %s', $item->get_date( 'j F Y | g:i a' ) ); ?>">
    					<?php echo esc_html( $item->get_title() ); ?>
    				</a>
    			</li>
    		<?php endforeach; ?>
    	<?php endif; ?>
    </ul>
    
  7. Execute the code and you should see the feed content displayed as shown in the image below.

    Feed content of W3Guy blog

Here’s the entire plugin code:


<h2>Blog Update from W3Guy</h2>

<?php
include_once( ABSPATH . WPINC . '/feed.php' );

// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed( 'https://w3guy.com/feed' );

if ( is_wp_error( $rss ) ) {
	return;
}

// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity( 5 );

// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items( 0, $maxitems );
?>

<ul>
	<?php if ( $maxitems == 0 ) : ?>
		<li><?php echo 'No feed item'; ?></li>
	<?php else : ?>
		<?php foreach ( $rss_items as $item ) : ?>
			<li>
				<a href="<?php echo esc_url( $item->get_permalink() ); ?>"
				   title="<?php printf( 'Posted %s', $item->get_date( 'j F Y | g:i a' ) ); ?>">
					<?php echo esc_html( $item->get_title() ); ?>
				</a>
			</li>
		<?php endforeach; ?>
	<?php endif; ?>
</ul>

Want to use the script, simply bundle it with a theme or plugin.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address