While developing your WordPress theme you might wish to add feeds from external sources that are relevant to the website/blog that will be using the theme. WordPress has inbuilt support for fetching external feeds.
The WordPress function fetch_feed is used to retrieve external feeds and parse them. The fetch_feed function uses the SimplePie and FeedCache functionality for retrieval, parsing and automatic caching. The fetch_feed function takes in the URL to the feeds source.
The following is the piece of code showing how you can retrieve external feeds in WordPress.
<?php // Include the file that contains the functions to be used // The following file must be included before you can use fetch_feed include_once(ABSPATH . WPINC . '/feed.php'); // Specify the feed source where the SimplePie object is to be got from $rss = fetch_feed('http://www.viiratech.com/feed'); if (!is_wp_error( $rss ) ) : // Check if the SimplePie object is well created. // Find the total feed items available, and limit it 10. $maxitems = $rss->get_item_quantity(10); // Build an array for the feeds items with 0 as the index of the first element. $rss_items = $rss->get_items(0, $maxitems); endif; ?> <?php if ($maxitems == 0) echo '<p>No Feeds Found.</p>'; else // Loop through the feed items and display links to the actual content. foreach ( $rss_items as $item ) : ?> <p> <a href='<?php echo esc_url( $item->get_permalink() ); ?>' title='<?php echo 'Date: '.$item->get_date('j F Y | g:i a'); ?>'> <?php echo esc_html( $item->get_title() ); ?></a> </p> <?php endforeach; ?>
The above code will retrieve 10 most recent feed items from “http://www.viiratech.com/feed” and display their titles hyperlinked to the actual content. You can change the feeds source from “http://www.viiratech.com/feed” to any other source where you wish to fetch the feeds from. Further more you can also change the feed item limit from 10 to the number of feeds you wish to fetch.
Note: WordPress by default caches the feeds items for relatively a long time (12 hours), and that means that feeds displayed on your website may be inaccurate in cases where you are retrieving feeds from websites that do frequent updates since your website will be showing cached feed items instead of retrieving a fresh copy of feeds from the set external source. This can be solve by changing the feed cache lifetime.
- Previous Post: Changing Feed Cache Lifetime In WordPress
- Next Post: Adding Theme Support In WordPress