Last active
May 17, 2022 10:42
-
-
Save 19h47/f24e765e49ce9b66f2a0aa81af9098ce to your computer and use it in GitHub Desktop.
Exclude posts from WordPress feed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
So you should use add_action
instead of add_filter
in this case, although one is just an alias of the other. 😉
Oh yeah you right. add_action
is more meaningful. We simply alter something, not add something. Thank you so much 🙏🏼
This saved my day. Thanks for taking the time to post it up!
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
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 👌🏼