Documentation Altering Feeds

Altering Feeds

Overview #

You may want to provide a custom RSS feed, or alter the content of an existing feed. The following examples show how easily this can be done by using some filters and actions.

↑ Top ↑

Custom Feeds #

To add new feeds to your site, use WordPress’s add_feed() function. It will handle a majority of the under-hood magic for you.

↑ Top ↑

Altering Existing Feeds #

/**
 * Example on how to implement custom feeds without code duplication
 * In this example a secondary feed that will return all posts of the last two weeks
 * with stripped out images will be implemented.
 * to access the feed use /feed/?show_custom_feed=two_weeks
 */

/**
 * Add custom variable 'my_show_custom_feed' which we will use to identify our feed.
 */
function my_add_custom_feed_var( $query_vars ) {
	$query_vars[] = 'my_show_custom_feed';
	return $query_vars;
}
add_action( 'query_vars', 'my_add_custom_feed_var' );

/**
 * Recognize feed and parameters and initialie actions accordingly.
 */
function my_change_custom_feed( $query ) {
	if ( $query->is_feed() && 'two_weeks' == $query->get( 'my_show_custom_feed' ) ) {
		// this filter is used to alter the where statement for the feed
		add_filter( 'posts_where', 'my_filter_last_two_weeks' );

		// the following two filters allow altering the content. in our example filtering images
		add_filter( 'the_content_feed', 'my_alter_feed_content' );
		add_filter( 'the_excerpt_rss', 'my_alter_feed_content' );

		// it would be also possible to alter the query directly via $query->set()
		// $query->set( 'cat', '123' ); // display only posts with category id 123
	}
	return $query;
}
add_filter( 'pre_get_posts', 'my_change_custom_feed' );

/**
 * Alter where query to limit posts to the last 14 days
 */
function my_filter_last_two_weeks( $where = '' ) {
	global $wpdb;
	$where .= $wpdb->prepare( " AND $wpdb->posts.post_date > %s", date( 'Y-m-d', strtotime( '-14 days' ) ) );
	return $where;
}

/**
 * Filter img tags from content and excerpt.
 */
function my_alter_feed_content( $content ) {
	$content = preg_replace( '#(<[/]?img.*>)#miU', '', $content );
	return $content;
}

↑ Top ↑

Modifying Images within Feeds #

Serve up larger sized images as part of the Media RSS component.

function my_remove_size_args_from_feed_featured_image( $medias ) {
	foreach ( $medias as $key => $media ) {
		// Skip items without a thumbnail, i.e. Gravatars and such
		if ( empty( $media['thumbnail'] ) )
			continue;

		// Make sure we have the required data
		if ( empty( $media['content'] ) || empty( $media['content']['attr'] ) || empty( $media['content']['attr']['url'] ) )
			continue;

		// Replace thumbnail URL with fullsize URL
		$image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
		$medias[$key]['content']['attr']['url'] = $image[0];
	}

	return $medias;
}
add_filter( 'mrss_media', 'my_remove_size_args_from_feed_featured_image', 15 );