Skip to content

Instantly share code, notes, and snippets.

@cgrymala
Created May 11, 2013 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgrymala/33bbd152ba2c05f859c6 to your computer and use it in GitHub Desktop.
Save cgrymala/33bbd152ba2c05f859c6 to your computer and use it in GitHub Desktop.
Retrieving and parsing RSS feed with SimplePie in WordPress
<?php
class Sample_WP_Feed_Parser {
var $source = 'http://www.example.com/feed/';
var $feed = null;
var $items = array();
/**
* Retrieve the appropriate items from the requested feed
*/
function fetch_feed() {
if ( ! $this->test_feed() )
return new WP_Error( 'feed-not-found', __( 'The requested feed could not be retrieved' ) );
if ( ! class_exists( 'SimplePie' ) )
require_once( ABSPATH . WPINC . '/class-feed.php' );
$this->feed = new SimplePie();
$this->feed->set_feed_url( $this->source );
$this->feed->set_cache_class( 'WP_Feed_Cache' );
$this->feed->set_file_class( 'WP_SimplePie_File' );
$this->feed->set_cache_duration( apply_filters( 'wp_feed_cache_transient_lifetime', 43200, $this->source ) );
do_action_ref_array( 'wp_feed_options', array( &$this->feed, $this->source ) );
$this->feed->init();
$this->feed->handle_content_type();
if ( $this->feed->error() ) {
return $this->feed = new WP_Error( 'simplepie-error', $this->feed->error() );
}
return $this->feed;
}
/**
* Process the requested feed items and turn them into slides
*/
function process_feed() {
$this->fetch_feed();
if ( is_wp_error( $this->feed ) )
return;
foreach( $this->feed->get_items( 0, 10 ) as $item ) {
$tmpimg = $item->get_enclosure();
if ( empty( $tmpimg ) || ! is_object( $tmpimg ) )
continue;
$img = array( 'src' => $tmpimg->get_link(), 'alt' => null );
$caption = array( 'title' => $item->get_title(), 'text' => $item->get_description() );
$link = array( 'url' => $item->get_permalink() );
$this->slides[] = new UMW_Home_Slide( $img, $caption, $link );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment