One of the things I love about WordPress is being able to do pretty much anything, and its built-in functions make this even easier. A few days ago I had the need to create a template to fetch and display posts from a feed. Despite being my first time doing something like this I got it working in a very short time. even more, I found a couple of ways to do this.

Option 1: WP_Http

The person who asked me to do the template left me a link to Ozh’s blog, where he explains how to use the WP_Http class to fetch content from external sites, a simple, well explained way. Once again, there’s more than one way to do this.

Using the class

The basic form (which Ozh explains in his article), is done by making a call to the class itself.

First we include the class (since WP 3.x)

    if( !class_exists( 'WP_Http' ) )
        include_once( ABSPATH . WPINC. '/class-http.php' );

Then we make the call and test the conection:

    $request = new WP_Http;
    $result = $request->request( 'http://feed.url' );

If succesful, then $result will be an array with the following data:

  • headers‘: Array with… headers… like "x-powered-by" => "PHP/5.2.1"
  • body‘: The feeds content, the thing we need. Returns Raw HTML
  • response‘: Array with the server’s response, we need array('code'=>200, 'message'=>'OK')
  • cookies‘: Array with cookies info.

Now the good stuff, the implementation:

function fetchFeed2($strFeedURL) { // Feed function
    if( !class_exists( 'WP_Http' ) ) // WP_Http Class
        include_once( ABSPATH . WPINC. '/class-http.php' ); // Include class
    $request = new WP_Http;
    $result = $request->request( $strFeedURL ); // test conection
    if ( ! is_wp_error($result) ) { // No error
        if ( ( $result['response']['code'] = 200 ) && ( $result['response']['message'] = "OK" ) ) { 
            return $result['body']; // get data
        } else {
            return  $result = "";
    } else { // error
        return  $result = "";
        $error_string = $result->get_error_message(); // which error was it?
        echo '<div id="message" class="error"><p>' . $error_string . '</p></div>'; // display error

Now we just have to add this where we want the feed to display.

    $strFeedURL = "http://feed.url";
    echo fetchFeed2($strFeedURL);

Easy right? source

Using functions

As I mentioned before, there’s more than one way to use this class, the other way is to use the functions (instead of the class itself), in this case wp_remote_get().

We could say this is the fastest way to use the class, we just need this code:

$response = wp_remote_get( 'http://feed.url' );
if( is_wp_error( $response ) ) { // error
    echo 'Something went wrong!';
    $error_string = $response->get_error_message(); // which error was it?
    echo '<div id="message" class="error"><p>' . $error_string . '</p></div>'; // display error
} else { // No error
    echo $response['body']; // Display content

The problem here is that (at least in my case) it returned the content in XML, and I’m not really good with that, how to turn it into simple html?

Option 2: Simplepie

Mi ultimate solution was to use other method, luckily we have Simplepie already integrated to WordPress, now we just have to call the function fetch_feed().

$rss = fetch_feed('http://feed.url');
if (!is_wp_error( $rss ) ) : // Was the object created?
    // How many items we got? (Max 5)
    $maxitems = $rss->get_item_quantity(5); 
    // Create an array with items starting with #0
    $rss_items = $rss->get_items(0, $maxitems); 

Let’s show the items, just like a WordPress loop

<?php if ($maxitems == 0) echo '<li>No items.</li>';
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
    <a href='<?php echo esc_url( $item->get_permalink() ); ?>'
    title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
    <?php echo esc_html( $item->get_title() ); ?></a>
<?php endforeach; ?>

This was with no doubts the easiest and fastest way since it allows me to customize almost entirely the way the items are displayed, the use is very similar to the WordPress loop and it supports a number of tags, every one listed in Simplepie’s documentation.

Mario Aguiar

Soy un Front-End developer, conferencista, y a veces escritor. Actualmente trabajo para 10up. Vivo en la hermosa ciudad de Aguascalientes, México. Puedes seguirme en Twitter @emeaguiar.

leer más