The add_feed() WordPress PHP function is used to add a new feed type like /atom1/.
Usage
Here’s how you could use the add_feed() function:
function add_custom_feed() { add_feed( 'custom', 'render_custom_feed' ); } add_action( 'init', 'add_custom_feed' );
In this example, ‘custom’ is the name of the feed, and ‘render_custom_feed’ is the function that will be called when the feed is accessed.
Parameters
- $feedname (string) – This is the name of your feed.
- $callback (callable) – This is the function that will be run when your feed is displayed.
More information
See WordPress Developer Resources: add_feed()
Note: When you add a new custom feed, the endpoint will render using a Content-Type: application/octet-stream; charset=UTF-8
by default. You can use header('Content-Type: application/rss+xml');
in your callback function to change this.
Examples
Basic usage
In this example, we are simply adding a new feed named ‘custom’.
function add_custom_feed() { add_feed('custom', 'render_custom_feed'); } add_action('init', 'add_custom_feed'); function render_custom_feed() { echo 'This is a custom feed!'; }
Changing content type
This example demonstrates how to change the content type of your feed.
function add_custom_feed() { add_feed('custom', 'render_custom_feed'); } add_action('init', 'add_custom_feed'); function render_custom_feed() { header('Content-Type: application/rss+xml'); echo 'This is a custom feed with RSS XML content type!'; }
Using add_filter()
In this example, we’re using the add_filter()
function to change the content type of our feed.
function add_custom_feed() { add_feed('custom', 'render_custom_feed'); } add_action('init', 'add_custom_feed'); function custom_feed_content_type( $content_type, $type ) { if('custom' == $type) { $content_type = 'application/rss+xml'; } return $content_type; } add_filter('feed_content_type', 'custom_feed_content_type', 10, 2); function render_custom_feed() { echo 'This is a custom feed with RSS XML content type, set with add_filter!'; }
Creating a feed from a custom WP Query
This example creates a feed from a custom WP Query, based on tags.
add_action('init', 'wpdocs_custom_feed_rss2'); function wpdocs_custom_feed_rss2() { add_feed('wpdocs_custom', 'wpdocs_change_main_query'); function wpdocs_change_main_query() { header('Content-Type: application/rss+xml'); global $wp_query; if (!empty($_GET['tag'])) { $tag = $_GET['tag']; } $wp_query = new WP_Query(array('post_type' => 'any', 'fields' => 'ids', 'tag' => $tag)); get_template_part('feed', 'rss2'); } }
Loading a template file for feed
This example shows how to load a specific template file for your feed.
function wpdocs_add_mwb_feed() { add_feed('mwbfeed', 'wpdocs_makewebbetter_feed'); }