Creating RSS Feed in Wordpress

From Fab Lab Wiki - by NMÍ Kvikan
Revision as of 10:25, 30 August 2014 by LinWan (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

As per definition, Wordpress is able to generate almost any RSS feed from whatever you want -- whole blog, single categories, tags, comments etc., you name it, all described here: http://codex.wordpress.org/WordPress_Feeds

Those feeds normally include all images that are inside a post ... however, when there are a number of images in the post's gallery (but not actually added into the post), those images are not part of the feed.

To fix this for our "HowTo" category (which is essentially the Fab Moments) I added a few tricks to generate a custom RSS feed for the how tos

  1. . add a template that generates the feed
  2. . announce the feed to aggregators

(1) I created a specific custom feed template that generates the XML with all images from the gallery. The template goes as follows:

<?php
/*
Template Name: Custom Feed
*/
 
$posts = query_posts('cat=9'); // selecting the HowTo category which is number 9
 
header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true);
$more = 1;

echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>

<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	<?php do_action('rss2_ns'); ?>
>

<channel>
	<title><?php bloginfo_rss('name'); wp_title_rss(); ?></title>
	<atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
	<link><?php bloginfo_rss('url') ?></link>
	<description><?php bloginfo_rss("description") ?></description>
	<lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
	<language><?php echo get_option('rss_language'); ?></language>
	<sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod>
	<sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency>
	<?php do_action('rss2_head'); ?>
	<?php while( have_posts()) : the_post(); ?>
	<item>
		<title><?php the_title_rss() ?></title>
		<link><?php the_permalink_rss() ?></link>
		<comments><?php comments_link_feed(); ?></comments>
		<pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
		<dc:creator><?php the_author() ?></dc:creator>
		<?php the_category_rss() ?>

		<guid isPermaLink="false"><?php the_guid(); ?></guid>
		<?php if (get_option('rss_use_excerpt')) : ?>
			<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
		<?php else : ?>
			<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
			<?php if ( strlen( $post->post_content ) > 0 ) : ?>
				<content:encoded><![CDATA[<?php the_content_feed('rss2') ?>]]></content:encoded>
			<?php else : ?>
				<content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded>
			<?php endif; ?>
		<?php endif; ?>
		<wfw:commentRss><?php echo esc_url( get_post_comments_feed_link(null, 'rss2') ); ?></wfw:commentRss>
		<slash:comments><?php echo get_comments_number(); ?></slash:comments>
		<?php function howto_addgallery_item() { // add here all images of the post gallery, code borrowed from Plugin MediaRSS
			global $howto_addgallery_gallery_lookup;
			$media = array();
			add_filter( 'wp_get_attachment_link', 'howto_addgallery_gallery_lookup', 10, 5 );
			$content = apply_filters( 'the_content', get_the_content() . "[gallery]" );
			remove_filter( 'wp_get_attachment_link', 'howto_addgallery_gallery_lookup', 10, 5 );
			$lookup = $howto_addgallery_gallery_lookup;
			unset($howto_addgallery_gallery_lookup);
			// img tags
			$images = 0;
			if ( preg_match_all('/<img (.+?)>/', $content, $matches) ) {
				foreach ( $matches[1] as $attrs ) {
					$item = $img = array();
					// Construct $img array from <img> attributes
					foreach ( wp_kses_hair($attrs, array('http')) as $attr )
						$img[$attr['name']] = $attr['value'];
					if ( !isset($img['src']) )
						continue;
					$img['src'] = howto_addgallery_url($img['src']);
					// Skip emoticons
					if ( isset( $img['class'] ) && false !== strpos( $img['class'], 'wp-smiley' ) )
						continue;
					$id = false;
					if ( isset( $lookup[$img['src']] ) ) {
						$id = $lookup[$img['src']];
					} elseif ( isset( $img['class'] ) && preg_match( '/wp-image-(\d+)/', $img['class'], $match ) ) {
						$id = $match[1];
					}
					if ( $id ) {
						// It's an attachment, so we will get the URLs, title, and description from functions
						$attachment =& get_post( $id );
						$src = wp_get_attachment_image_src( $id, 'full' );
						if ( !empty( $src[0] ) )
							$img['src'] = $src[0];
						$thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' );
						if ( !empty( $thumbnail[0] ) && $thumbnail[0] != $img['src'] )
							$img['thumbnail'] = $thumbnail[0];
						$title = get_the_title( $id );
						if ( !empty( $title ) )
							$img['title'] = trim($title);
						$description = get_the_content( $id );
						if ( !empty( $attachment->post_excerpt ) )
							$img['description'] = trim($attachment->post_excerpt);
					}
					// If this is the first image in the markup, make it the post thumbnail
					if ( ++$images == 1 ) {
						if ( isset( $img['thumbnail'] ) )
							$media[]['thumbnail']['attr']['url'] = $img['thumbnail'];
						else
							$media[]['thumbnail']['attr']['url'] = $img['src'];
					}
					$item['content']['attr']['url'] = $img['src'];
					$item['content']['attr']['medium'] = 'image';
					if ( !empty($img['title']) ) {
						$item['content']['children']['title']['attr']['type'] = 'html';
						$item['content']['children']['title']['children'][] = $img['title'];
					} elseif ( !empty($img['alt']) ) {
						$item['content']['children']['title']['attr']['type'] = 'html';
						$item['content']['children']['title']['children'][] = $img['alt'];
					}
					if ( !empty($img['description']) ) {
						$item['content']['children']['description']['attr']['type'] = 'html';
						$item['content']['children']['description']['children'][] = $img['description'];
					}
					if ( !empty($img['thumbnail']) )
						$item['content']['children']['thumbnail']['attr']['url'] = $img['thumbnail'];
					$media[] = $item;
				}
			}
			$media = apply_filters('howto_addgallery_media', $media);
			howto_addgallery_print($media);
		}

		function howto_addgallery_url($url) {
			if ( preg_match( '!^https?://!', $url ) )
				return $url;
			if ( $url{0} == '/' )
				return rtrim( get_bloginfo('home'), '/' ) . $url;
			return get_bloginfo('home') . $url;
		}

		function howto_addgallery_gallery_lookup($link, $id, $size, $permalink, $icon) {
			global $howto_addgallery_gallery_lookup;
			preg_match( '/ src="(.*?)"/', $link, $matches );
			$howto_addgallery_gallery_lookup[$matches[1]] = $id;
			return $link;
		}

		function howto_addgallery_print($media) {
			if ( !empty($media) )
				foreach( $media as $element )
					howto_addgallery_print_element($element);
			echo "\n";
		}

		function howto_addgallery_print_element($element, $indent = 2) {
			echo "\n";
			foreach ( $element as $name => $data ) {
				echo str_repeat("\t", $indent) . "<media:$name";
				if ( !empty($data['attr']) ) {
					foreach ( $data['attr'] as $attr => $value )
						echo " $attr=\"" . esc_attr(ent2ncr($value)) . "\"";
				}
				if ( !empty($data['children']) ) {
					$nl = false;
					echo ">";
					foreach ( $data['children'] as $_name => $_data ) {
						if ( is_int($_name) ) {
							echo ent2ncr(esc_html($_data));
						} else {
							$nl = true;
							howto_addgallery_print_element( array( $_name => $_data ), $indent + 1 );
						}
					}
					if ( $nl )
						echo "\n" . str_repeat("\t", $indent);
					echo "</media:$name>";
				} else {
					echo " />";
				}
			}
		}

		howto_addgallery_item(); ?>

		<?php rss_enclosure(); ?>
		<?php do_action('rss2_item'); ?>
	</item>
	<?php endwhile; ?>
</channel>
</rss>

(2) Then I added the custom feed for HowTos so the site announces the feed to aggregators -- as per instructions here: http://www.seodenver.com/custom-rss-feed-in-wordpress/

Adding the following code snippet to the function.php in the active template directory.

function create_my_customfeed() {
	load_template( TEMPLATEPATH . 'customfeed.php'); // You'll create a customfeed.php file in your theme's directory
}
add_action('do_feed_customfeed', 'create_my_customfeed', 10, 1); // Make sure to have 'do_feed_customfeed'