Mar 23, 2019

WordPress: Customize Title in RSS Feed and Get it from Excerpt

Recently, I introduced #TechBrijTips, A micro-blogging section on this website which has content like twitter posts. It is different from regular blog posts as it doesn't have any specific title. So I had a question what to display in the RSS feed of WordPress. It doesn't look good to me to display first few words of the main content. I decided to display title from Excerpt. In this post, we will see how to implement it.

We are going to use the_title_rss hook to filter the post title for use in a feed.


add_filter( 'the_title_rss', 'custom_feed_title' );

Let's start with a simple function which adds TechBrij prefix in the existing title of any post type:


function custom_feed_title( $title ) {
  return 'TechBrij: '. $title;
}

The output is for regular blog-posts feed:


<item>
		<title>TechBrij: RabbitVCS: A TortoiseGit for Ubuntu</title>
...
</item>
<item>
		<title>TechBrij: Introducing #TechBrijTips for Micro-blogging</title>

...
</item>

Let's update the title based on post type


function custom_feed_title( $title ) {
  global $wp_query;
  if ($wp_query->post->post_type == 'tip'){    
    return 'Tips: '. $title;
  }
  else{
    return $title;
  }
}

and output of regular feed doesn't have TechBrij prefix which we added earlier:


<item>
		<title>RabbitVCS: A TortoiseGit for Ubuntu</title>
...
</item>
<item>
		<title>Introducing #TechBrijTips for Micro-blogging</title>

...
</item>

Let's get Excerpt as title for Tips:


function custom_feed_title( $title ) {
  global $wp_query;
  if ($wp_query->post->post_type == 'tip'){    
    return  esc_html($wp_query->post->post_excerpt);
  }
  else{
    return $title;
  }
}

In feed of Tips post type, you will get excerpt:


<item>
		<title>How to get posts by  multiple tag/category queries in Wordpress from URL</title>
...
</item>
<item>
		<title>VSCode useful shortcut To navigate back to previous cursor position</title>
...
</item>

Excerpt might be too long for title, let's add ellipsis for long excerpt:



function custom_feed_title( $title ) {
  global $wp_query;
  if ($wp_query->post->post_type == 'tip'){   
    $title =  $wp_query->post->post_excerpt;
    if( strlen( $title) > 50) {
      $str = explode( "\n", wordwrap(  $title, 50));
      $title = $str[0] . '...';
    }  
    return  esc_html($title);
  }
  else {
    return $title;
  }
}


Here is the final output:


<item>
		<title>How to get posts by  multiple tag/category queries...</title>
...
</item>
<item>
		<title>VSCode useful shortcut To navigate back to...</title>
...
</item>

Firefox displays RSS feed in readable format:

Wordpress rss feed customize

In this tutorial, we saw how to customize WordPress feed title using simple hooks. Don't forget to subscribe #TechBrijTips Feed.

Enjoy WordPress!!