Create a gist now

Instantly share code, notes, and snippets.

How to add a custom feed to WordPress
<?php
/**
* Add a custom feed to WordPress.
*
* The feed will be rendered through the wp-includes/feed-rss2.php template
* and avaiable under example.com/feed/{$feed_slug}.
*
* Note: Don't forget to flush the rewrite rules once.
*
* @author Dominik Schilling
* @link http://wpgrafie.de/897
*/
class DS_Custom_Feed {
/**
* Sets the feed slug.
*
* @var string
*/
public static $feed_slug = 'custom';
/**
* Registers the feed and the pre_get_posts action
*/
public static function init() {
add_feed( self::$feed_slug, array( __CLASS__, 'feed_template' ) );
add_action( 'pre_get_posts', array( __CLASS__, 'feed_content' ) );
}
/**
* Customizes the query.
* It will bail if $query is not an object, filters are suppressed and it's not
* our feed query.
*
* @param WP_Query $query The current query
*/
public static function feed_content( $query ) {
// Bail if $query is not an object or of incorrect class
if ( ! $query instanceof WP_Query )
return;
// Bail if filters are suppressed on this query
if ( $query->get( 'suppress_filters' ) )
return;
// Bail if it's not our feed
if ( ! $query->is_feed( self::$feed_slug ) )
return;
// Change the feed content
// Example: A feed for pages
$query->set( 'post_type', array( 'page' ) );
}
/**
* Loads the feed template which is placed in wp-includes/feed-rss2.php.
*/
public static function feed_template() {
load_template( ABSPATH . WPINC . '/feed-rss2.php' );
}
}
/**
* Hooks into `init`.
*
* Note: add_feed() needs access to the global $wp_rewrite
*/
add_action( 'init', array( 'DS_Custom_Feed', 'init' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment