There are many reason’s you might need to create a custom feed in WordPress. You may need a feed in an unusual or non-standard format, or you may want to add or edit the content of your feeds. Setting up a custom feed is pretty easy, but poorly documented.
Everything revolves around the add_feed
function. This function takes two arguments: a name for your feed and a function to call to create the feed:
add_feed('myFeed', 'myPlugin_create_feed');
The function from the latter argument will handle all of the work of creating your feed. It will have access to the WordPress loop, so after calling have_posts()
and the_post()
, you can take advantage of all the template tags available.
When to call add_feed
For add_feed
to work, you have to wait until WordPress has completely initialized before you call it. You can use the init
action hook to accomplish this at the right time.
add_action('init', 'myPlugin_add_feed'); function myPlugin_add_feed( ) { add_feed('myFeed', 'myPlugin_create_feed'); }
Changing Rewrite Rules
If you stopped there, WordPress would call myPlugin_create_feed()
whenever you go to a page and add the query string feed=myFeed
to the end of the URL. Example: http://example.com/?feed=myFeed
or http://example.com/?s=foo&feed=myFeed
.
If you want to make the URL for your feed look like the other feeds in WordPress (e.g., http://example.com/feed/atom
), you have to change the rewrite rules.
To tell WordPress to add new rules, use the generate_rewrite_rules
action hook. It will call your function just before it finishes building its rules, with the $wp_rewrite
object as an argument. Simply add your new rule to the pre-existing $wp_rewrite->rules
array.
function myPlugin_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'feed/(.+)' => 'index.php?feed='.$wp_rewrite->preg_index(1) ); $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; }
You can add this action hook into your myPlugin_add_feed
function. Finally, you need to tell WordPress to rebuild its rewrite rules now that it has your additions, using $wp_rewrite->flush_rules()
.
function myPlugin_add_feed( ) { global $wp_rewrite; add_feed('myFeed', 'myPlugin_create_feed'); add_action('generate_rewrite_rules', 'myPlugin_rewrite_rules'); $wp_rewrite->flush_rules(); }
Now your customized feed should be accessible at http://example.com/feed/myFeed
.