We had a client recently request that we embed an RSS feed from a different site inside their WordPress install. This would’ve been very easy considering there are 100’s of RSS feed plugins that will accomplish this task. However, they wanted to only display RSS items that had certain keywords in the title. My initial search found no WP plugins that currently were capable of this. I also tried one of the more popular ones, FeedList, but it used the get_rss() function in the WordPress API. For some reason, this function was not properly parsing the feed they wanted to use, most likely due to it not being a valid feed.
So to make a long story short: I decided to make a quick hack up solution and write my own WP plugin. My only hurdle-like requirement is that it had to work for PHP4 as well because the client is on one of our older servers. I ended up finding a really good example by Ryan Stemkoski. He wrote a perfect function for me to tweak a little and expand upon. I am currently waiting to get approved on WordPress extend so I can host my plugin there. For now, I have created a page here where you can download the plugin.
Note: I haven’t tested this in a more recent version of WP yet but I will be soon. Let me know if you find any bugs!
I also figured I would post the source code in case someone needed a quick and dirty solution with some examples.
rss_lib.php
<?php
/*
* RSS Parsing Function
*
* Original Author: Ryan Stemkoski
* http://www.stemkoski.com/how-to-easily-parse-a-rss-feed-with-php-4-or-php-5/
*
* Slight modifications by Jesse R. Adams (DualTech Services, Inc.)
*/
function parseRSS($url) {
//PARSE RSS FEED
$feedeed = implode('', file($url));
$parser = xml_parser_create();
xml_parse_into_struct($parser, $feedeed, $valueals, $index);
xml_parser_free($parser);
//CONSTRUCT ARRAY
foreach($valueals as $keyey => $valueal){
if($valueal['type'] != 'cdata') {
$item[$keyey] = $valueal;
}
}
$i = 0;
foreach($item as $key => $value){
if($value['type'] == 'open') {
$i++;
$itemame[$i] = $value['tag'];
} elseif($value['type'] == 'close') {
$feed = $values[$i];
$item = $itemame[$i];
$i--;
if(count($values[$i])>1){
$values[$i][strtolower($item)][] = $feed;
} else {
$values[$i][strtolower($item)] = $feed;
}
} else {
$values[$i][strtolower($value['tag'])] = $value['value'];
}
}
//RETURN ARRAY VALUES
return $values[0];
}
/*
* Convert Raw RSS Parse into concise list of items
*
* Optionally pass in limit (on number of items)
* and/or array list of words to grab items by.
*
*/
function extractRSSItems($xmlArray, $limit = null, $filteredWords = array()) {
$array = array();
$regex = null;
if (count($filteredWords) > 0) {
$regex = implode('|', $filteredWords);
}
foreach($xmlArray['rss']['channel']['item'] as $item) {
if (!$regex || ($regex && preg_match("/$regex/i", $item['title']))) {
$array[] = $item;
}
}
if($limit) {
array_splice($array, ($limit - 1), (count($array) - $limit));
}
return $array;
}
?>
selective_rss.php
<?php
/*
Plugin Name: Selective RSS
Plugin URI: http://techno-geeks.org/selective-rss
Description: Simple Plugin that allows you to embed RSS feed items into Pages or Posts. Optionally allows you to choose how many items to display and allows you to limit items to ones that contain certain words in the titles.
Version: 0.1.0b
Author: Jesse R. Adams (DualTech Services, Inc.)
Author URI: http://www.dual-tech.com/about-dualtech-services/
*/
require_once('rss_lib.php');
function filter_feeds($content) {
$limit = null;
$filter = array();
$url = null;
$inputTag = preg_match('/\[srss (.+)\]/', $content, $matches);
$rawArgs = explode(',', $matches[1]);
foreach($rawArgs as $input) {
preg_match_all('/^(url|filter|limit)=(.+)$/i', $input, $matches);
$key = $matches[1][0];
$value = $matches[2][0]
if ($key == 'filter') {
$filter = explode(';', $value);
} else {
$$key = $value;
}
}
if ($url) {
$xml = parseRSS($url);
$items = extractRSSItems($xml, $limit, $filter);
$htmlToAdd = '';
foreach ($items as $item) {
$htmlToAdd .= '<a href="' . $item['link'] . '" target="new">' . $item['title'] . '</a>' . "<br/>\n";
$htmlToAdd .= $item['description'] . "<br/><br/>\n";
}
$content = preg_replace('/\[srss .+\]/', $htmlToAdd, $content);
}
return $content;
}
add_filter('the_content', 'filter_feeds');
?>
Update 06/19: Fixed the way arguments are parsed to be less limiting on possibilities.
Hi,
I tried the selective rss plugin for my site.. I added 5 different rss feeds in a page but all displaying the first feed five different times.
Please Help…
@Sheik: I sent you an email regarding the potential bug you found. As soon as you provide more info I’ll figure out the fix.
Tengo varias dudas. Termine de instalar este plugin y desearia saber que debo hacer ahora para incluir RSS en mi web. Es decir quiero que a traves del RSS queden suscriptos a para ver actualizaciones a mis contenidos.
Gracias
¿Es usted querer incluir otros pueblos RSS en una página o un mensaje en su sitio web? ¿O usted está queriendo utilizar el built-in RSS WordPress que genera para su sitio web? He utilizado un traductor de modo pido disculpas por mi gramática.
Hi, I have added your plugin to WP and tested it with my RSS Twitter feed. If any limit is ser, always is displayed the oldest post. (IE when I set limit=1 only the oldest post is displayed, when I set limit=2 both latest ond oldest post are displayed, and so on.)
Doesn’t seem to be working with yahoo pipes. I get the following error:
Warning: Invalid argument supplied for foreach() in /wp-content/plugins/selective-rss/rss_lib.php on line 73
Can you extend this plugin to have it display RSS items that have certain keywords in the title OR in the content?
I and most probably many other people, would appriciate that very much!!!
Hello!
Your WP Plugin, would incerdible, the only problem is, doesn’t work with new wordpress (2.9.2)
If you have free time to make compatibile with new WP versions, many people will be happy.
Thank you forward!
Tompy
Help! I’m getting this with ONE page that uses your plugin.
Warning: Invalid argument supplied for foreach() in /home/mvoof/public_html/zoomdweebies.com/wp-content/plugins/selective-rss/rss_lib.php on line 73
Warning: Invalid argument supplied for foreach() in /home/mvoof/public_html/zoomdweebies.com/wp-content/plugins/selective-rss/rss_lib.php on line 73
Warning: Cannot modify header information – headers already sent by (output started at /home/mvoof/public_html/zoomdweebies.com/wp-content/plugins/selective-rss/rss_lib.php:73) in /home/mvoof/public_html/zoomdweebies.com/wp-includes/pluggable.php on line 890
Two other pages, using the same exact shortcode with a different url for the feed work FINE. I’m stumped.