Custom RSS feeds in WordPress

June 12, 2009 · Print This Article

RSS feeds are very useful and very popular. WordPress creates RSS feeds by default, but how to create your own, custom RSS Feed?

If you need a custom RSS feed, like for example, a feed indexing only somes categories and tags, or if you redirected all WordPress RSS feeds to Feedburner but still want to be able to get a category feed, there’s an easy solution though, just follow these steps:

  1. create a custom page template within your theme that serves out the feed (code below)
  2. create a new page (which can be blank), with a secret URL
  3. use your newly created “Custom Feed” template for that page
  4. open the secret URL in your browser

Simply paste the following code in a new file, save it under the name custom-feed.php and upload it on your theme directory.

Once done, simply write a new page in WordPress Dashboard (Don’t type any text it in), and select custom-feed.php as a page template.

<?php
/*
Template Name: Custom Feed template
*/

$numposts = 5;

function livexp_rss_date( $timestamp = null ) {
  $timestamp = ($timestamp==null) ? time() : $timestamp;
  echo date(DATE_RSS, $timestamp);
}

function livexp_rss_text_limit($string, $length, $replacer = '...') {
  $string = strip_tags($string);
  if(strlen($string) > $length)
    return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
  return $string;
}

$posts = query_posts('showposts='.$numposts);

$lastpost = $numposts - 1;

header("Content-Type: application/rss+xml; charset=UTF-8");
echo '<?xml version="1.0"?>';
?><rss version="2.0">
<channel>
  <title>Live Experience E-mail Update</title>
  <link>http://livexp.net/</link>
  <description>The latest blog posts from livexp.net.</description>
  <language>en-us</language>
  <pubDate><?php livexp_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></pubDate>
  <lastBuildDate><?php livexp_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></lastBuildDate>
  <managingEditor>info@livexp.net</managingEditor>
<?php foreach ($posts as $post) { ?>
  <item>
    <title><?php echo get_the_title($post->ID); ?></title>
    <link><?php echo get_permalink($post->ID); ?></link>
    <description><?php echo '<![CDATA['.livexp_rss_text_limit($post->post_content, 500).'<br/><br/>Keep on reading: <a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>'.']]>';  ?></description>
    <pubDate><?php livexp_rss_date( strtotime($post->post_date_gmt) ); ?></pubDate>
    <guid><?php echo get_permalink($post->ID); ?></guid>
  </item>
<?php } ?>
</channel>
</rss>


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.