Exclude Post from WordPress Feed – WP Engineer Exclude Post from WordPress Feed – WP Engineer

Exclude Post from WordPress Feed – WP Engineer


In a previous post I provide a solution on how to exclude certain categories from your feed. You can do the same with other content and I will show you in this post how you can exclude certain posts from your feed.

Therefore I use the filter posts_where (wp-includes/query.php), which is responsible for the output of the query. Please be aware that you should only filter, where you want to filter; In our example it is in our feed $wp_query->is_feed. If you won’t do it that way, the filter would also run in your backend and these posts won’t be displayed on post overviews.

The function has two parameters and you give the first parameter $where an extension of the SQL-string, which will take care of the filtering based on the ID. Within the brackets you have to put in the IDs of the posts, which you like to filter.


function fb_post_exclude($where, $wp_query = NULL) {
	global $wpdb;
	
	if ( !$wp_query )
		global $wp_query;
	
	if ($wp_query->is_feed) {
		// exclude post with id 40 and 9
		$where .= " AND $wpdb->posts.ID NOT IN (40, 9)";
	}
	
	return $where;
}
add_filter( 'posts_where','fb_post_exclude', 1, 2 );

Have fun with testing and adjustments of the code. The function is pretty small but it nicely shows the possibilities and you can extend it to your liking.

Update: please use for this requirement the follow solution and read the comments for this solution without SQL statement; use the filter pre_get_posts.


function fb_exclude_filter($query) {
    if ( !$query->is_admin && $query->is_feed) {
        $query->set('post__not_in', array(40, 9) ); // id of page or post
    }
    return $query;
}
add_filter( 'pre_get_posts', 'fb_exclude_filter' );