Creating a Custom Feed in WordPress

Ever find yourself wanting to create a custom feed of your WordPress managed website? Lucky for you they have the handy add_feed hook that allows you to define as many feeds as you want, Just be careful not to duplicate any existing feeds. I personally find myself using this feature to output xml of data that I then utilize in Flash presentations. The add_feed function works like all other WordPress hooks in that it calls the user defined function when the named feed is to be rendered.

For illustration purposes lets walk through the basic steps for creating a Custom Feed.

Define a function to output the xml

Before adding the feed you first need to define the function that will render the xml to be returned when the feed is called. Depending on your needs you can define this in a custom plugin or in the functions file of your theme. The below snippet outputs your posts in a basic xml structure.

function outputXMLFeed()
{
    $posts = query_posts('showposts=5');
 
    echo '<?xml version="1.0"?>';
    echo '<items>';
    foreach ($posts as $post) {
        echo '<item>';
        echo '<title>' . get_the_title($post->ID) . '</title>';
        echo '<link>' . permalink($post->ID) . '</link>';
        echo '<guid>' . get_permalink($post->ID) . '</guid>';
        echo '</item>';
    }
    echo '</items>';
}

Add the feed to WordPress

Now to add the feed we simply need to call add_feed where we pass in the name of the feed and the function that will output the feed contents (xml). One caveat exists however in that WordPress needs to be fully initialized before the add_feed function can be called. This forces us to wrap up the add_feed call behind another function that gets called on the WordPress init hook.

add_action('init', 'add_my_feed');
 
function add_my_feed(  ) {
  add_feed("myFeed", "outputXMLFeed");
}

Calling your Custom Feed

To access your feed you simply need to append ?feed=Name of your Feed to your site’s url. In this case the final url would be http://www.example.com/?feed=myFeed

That is all there is to creating your custom feeds. Depending on your needs you can create them in your theme functions or in a standalone plugin. If you are using additional plugins like Pods CMS then feeds can be extremely useful in rendering pods contents into xml for use by Flash, JavaScript or other applications.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>