Add Custom Post Type into Feed

Advertisement

WordPress provide the reed support with URL. We can see the site feed with below URL pattern:

https://mywebsite.com/feed/

The /feed/ is generated from the WordPress PHP file wp-includes\feed-rss2.php

The have_posts() loop is executed while generating the feed. So, We can use the filter pre_get_posts to show our custom post type feed.

Below is the sample code which add the post, astra-portfolio, and deal post types into the feed.

<?php
/**
* Add Custom Post Types (CPT) to feeds
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @return object
*/
if( ! function_exists( 'prefix_add_custom_post_types_to_feed' ) ) :
function prefix_add_custom_post_types_to_feed( $query ) {
// Is feed then add custom post types.
if ( is_feed() ) {
$query->set( 'post_type', array( 'post', 'astra-portfolio', 'deal' ) );
}
return $query;
}
add_filter( 'pre_get_posts', 'prefix_add_custom_post_types_to_feed' );
endif;

Leave a Reply