Jetpack: Add Related Posts to your RSS feed
Last updated 11 months ago
PHP
/**
* Add Jetpack Related Posts to RSS feed.
*
* @see https://wordpress.org/support/topic/2927523
*
* @param string $content Post content.
*/
function hlabs_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', 'hlabs_related_posts_feed' );
All code snippets are licensed GPLv2 or later unless otherwise stated.