Skip to content

Instantly share code, notes, and snippets.

@ocean90
Last active May 30, 2019 22:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ocean90/4973288 to your computer and use it in GitHub Desktop.
Save ocean90/4973288 to your computer and use it in GitHub Desktop.
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