bhubbard
7/20/2016 - 4:05 PM

Add Jetpack Related Posts to RSS feed. https://jeremy.hu/jetpack-related-posts-rss-feed/

Add Jetpack Related Posts to RSS feed. https://jeremy.hu/jetpack-related-posts-rss-feed/

<?php

/**
 * Add Jetpack Related Posts to RSS feed.
 *
 * @see https://wordpress.org/support/topic/2927523
 */
function jeherve_related_posts_feed( $content ) {
    // Return early if we're not in the RSS feed.
    if ( ! is_feed() ) {
        return $content;
    }
 
    // If Jetpack and Related Posts are active, let's get started.
    if ( class_exists( 'Jetpack_RelatedPosts' ) && method_exists( 'Jetpack_RelatedPosts', 'init_raw' ) ) {
        $related = Jetpack_RelatedPosts::init_raw()
            ->set_query_name( 'jetpackme-shortcode' ) // Optional, name can be anything
            ->get_for_post_id(
                get_the_ID(),
                array( 'size' => 3 )
            );
 
        if ( $related ) {
            $related_list = '';
 
            foreach ( $related as $result ) {
                // Get the related post IDs
                $related_post_id = get_post( $result[ 'id' ] );
 
                /**
                 * From there you can do just about anything, using the post IDs.
                 *
                 * In this example, we'll build an unordered list.
                 */
                $related_list .= sprintf(
                    '<li><a title="%1$s" href="%2$s">%3$s</a></li>',
                    esc_attr( get_the_title( $related_post_id ) ),
                    get_permalink( $related_post_id ),
                    get_the_title( $related_post_id )
                );
            }
 
            /**
             * Let's wrap all those related posts in ul tags, and add that list to the end of our post content.
             *
             * We will also add a headline, but only if it was set to be displayed in your Jetpack Related Posts settings.
             */
            $related_options = Jetpack_Options::get_option( 'relatedposts' );
            if ( $related_options['show_headline'] ) {
                $headline = sprintf(
                    '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
                    esc_html__( 'Related', 'jetpack' )
                );
            } else {
                $headline = '';
            }
 
            return sprintf(
                '%1$s%2$s<ul class="jp-relatedposts">%3$s</ul>',
                $content,
                apply_filters( 'jetpack_relatedposts_filter_headline', $headline ),
                $related_list
            );
        }
 
        return $content;
    }
 
    // Last fallback, just in case Jetpack and Related Posts aren't there anymore.
    return $content;
}
add_filter( 'the_content', 'jeherve_related_posts_feed' );