Create a RSS Feed System

Tired of the default WordPress RSS Feed system bogged down with custom types and really just does not do want you want. After the Woo Theme’s ecommerce plugin WooCommerce started putting all the PayPal transactions into the RSS Feed, I decided I needed to change it. This tutorial shows how I did it using the Web API plugin.

To start, create a new API post as in the documentation for the Web API plugin. You can call the new API post ‘feed’. Now place this code in that post content area:

//
// Set up the Loop for going through the posts and tutorials. The other
// post types in the system will be ignored. We set the post types to
// display by the 'post_type' array key set to another array of post types.
// If you just want one type of post, you do not need to use an array.
//
$loop = new WP_Query( array(
   'post_type' => array('tutorials', 'post'),
   'orderby' => 'date',
   'order' => 'DESC',
  'post_status' => 'publish'
));

//
// Get the encoding format for this blog.
//
$charset = get_option('blog_charset');

//
// Set the header for a RSS2 feed.
//
header("Content-Type: rss2; charset={$charset}", true);

//
// Set the xml version and encoding.
//
echo '';

//
// Jump into HTML to set the basic header. Most of this is static and is
// easier to encode directly in HTML mode. The inline PHP code will set
// the dynamic content and is fairly self-explanitory.
//
?>




	<?php bloginfo('name'); wp_title(); ?>
	
	
	
	
	english
	hourly
	1
	have_posts()) : $loop->the_post(); ?>
	
		<?php the_title() ?>
		
		
		
		]]>
		]]>
	
	


Let’s walk through the code some:

Lines 7-12: This line queries the database for the type of posts that we want to show in the RSS feed. I have it set to ‘post’ and ‘tutorials’. The ‘post’ post type is the standard post in WordPress, while ‘tutorials’ is a custom post type that I developed for my site.

Lines 17-54: This setups the standard header formats and content descriptions as specified in the RSS2 specification.

Lines 55-end: This is the main part of the code. It loops through each post in a while loop and exports the proper lines for making the RSS2 feed. This area really shows how to embed your PHP inside of the HTML elements that make up the feed.

Once you publish the API post, you can set the address of the page in your theme for your RSS feed for your site. The address for your new feed will by {your-site-address}/API/feed/. The ‘feed’ on the end is the slug for your custom Web API page. On this system, it is ‘feed-2′ because I already had an article with the slug ‘feed’ in it. If you want to see the raw output of the script, just click on View API (not currently available) at the top of the API post page.

That is it! Now you can take this code and change it anyway that you want. This is just to get you started.

comments powered by Disqus