Skip to content

Instantly share code, notes, and snippets.

@19h47
Last active May 17, 2022 10:42
Show Gist options
  • Save 19h47/f24e765e49ce9b66f2a0aa81af9098ce to your computer and use it in GitHub Desktop.
Save 19h47/f24e765e49ce9b66f2a0aa81af9098ce to your computer and use it in GitHub Desktop.
Exclude posts from WordPress feed
<?php // phpcs:ignore
add_action( 'pre_get_posts', 'exclude_posts_from_feed', 10, 1 );
/**
* Exclude posts from feed
*
* Exclude posts from feed based on a boolean metadata (maybe set by an ACF
* field): exclude_from_feed
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*
* @see https://developer.wordpress.org/reference/hooks/pre_get_posts/
*
* @return void
*/
function exclude_posts_from_feed( WP_Query $query ) : void {
if ( ! $query->is_feed ) {
return;
}
if ( 'post' !== $query->get( 'post_type' ) ) {
return;
}
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'exclude_from_feed',
'value' => '',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'exclude_from_feed',
'value' => '0',
'compare' => '==',
),
);
$query->set( 'meta_query', $meta_query );
}
@19h47
Copy link
Author

19h47 commented Nov 19, 2019

Oh thank you! I always wonder if I have to return something at the end of a pre_get_posts action. Like a continue or something. Now I know 👌🏼

@Djules
Copy link

Djules commented Nov 19, 2019

So you should use add_action instead of add_filter in this case, although one is just an alias of the other. 😉

@19h47
Copy link
Author

19h47 commented Nov 19, 2019

Oh yeah you right. add_action is more meaningful. We simply alter something, not add something. Thank you so much 🙏🏼

@decaySmash
Copy link

This saved my day. Thanks for taking the time to post it up!

@19h47
Copy link
Author

19h47 commented May 17, 2022

This saved my day. Thanks for taking the time to post it up!

You're welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment