How to Create a Custom Feed in WordPress (without a Plugin)
A post over at CSS Tricks got me thinking about creating custom WordPress feeds without using a plugin (like Feed Wrangler, which works great if you don’t want to go through the “work” below). So I did some digging and figured it out.
First, let’s open up our functions.php file and add some code:
function the_new_feed() {
add_feed('newfeed', 'a_new_feed');
}
add_action('init', 'the_new_feed');
function a_new_feed() {
add_filter('pre_option_rss_use_excerpt', '__return_zero');
load_template( TEMPLATEPATH . '/feeds/a-feed-template.php' );
}
What does that do?
add_feed
is a native WP function, that adds a feed. Kinda…- We have to hook into the
init
action of WordPress to get it setup. - Then we create the
a_new_feed()
custom function to tell WP what to base our feed off of (ie, the code with the loop).
Next, we need to create a template as per our load_template
call above. To do this:
- Create a new folder in your theme’s directly called “feeds”.
- Create a file in that folder called “a-feed-template.php”
- Open up “wp-includes/feed-rss2.php”, and copy the contents of that file into your new “a-feed-template.php” file.
- Save the file.
- Then in WordPress, go to Settings > Permalinks and click Save Changes. This does the necessary rewrite flush we need to make everything above kick in.
You’ve not got a new feed at http://yoursite.com/feed/newfeed/
You can use query_post
or whatever else you’d like to do in that new template file to alter the output of the feed. Add images, only show certain post types, etc.