How to customize wordpress rss feed

By defaul WordPress will include all posts sorted by creation time for rss feed. If you want to customize wordpress feed, you can write custom code to include wordpress pages, skip specific entries, etc. Here are steps to customize wordpress feed for few cases:

Include pages in wordpress feed

To incluse wordpress pages to feed, we can use pre_get_posts hook as shown below:

function pre_get_posts_rss ($query) {
  if (is_feed() ) {
    $query->set('post_type', array('post', 'page'));
  }
}
add_action('pre_get_posts', 'pre_get_posts_rss');

Change posts per rss wordpress feed

To change posts per rss, we can add filter to pre_option_posts_per_rss and set the desired value as shown below:

add_filter('pre_option_posts_per_rss', function() { return 30;});

Skip certain posts based on meta key

In case you want to skip some post based on meta key or other custom logic, you can attach hook to posts_results. In the following code we’ll skip post which have meta key skip_rss. We’ll also skip non-leaf pages.

function posts_results_rss( $posts ) {
  if (!is_feed() ) {
    return $posts;
  }
  $filtered_posts = array();
  foreach ( $posts as $post ) {
    $skip_rss = get_post_meta($post->ID, 'skip_rss', true);
    $is_leaf = _is_leaf_page($post->ID);
    if (!$skip_rss && $is_leaf) {
      $filtered_posts[] = $post;
    }
    if (count($filtered_posts) >= 10) {
      break;
    }
  }
  return $filtered_posts ;
}
add_filter( 'posts_results', 'posts_results_rss' );

Note that for this logic to work properly, you need to increase posts per rss so that we get enough entries in function posts_results_rss. Implementation for function _is_leaf_page can see seen in article Find if a wordpress is leaf.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments