Archived topic
Remove Specific Post From Blog Page
14 replies · Started by Caitriona on June 20, 2022
I am trying to remove a specific post from my blog page. How do I do it?
Hi there,
try this PHP Snippet:
function excludePostId($query) {
$postIds = array(
66
);
if ( $query->is_home() && $query->is_main_query() ) {
set_query_var('post__not_in', $postIds);
}
}
add_action('pre_get_posts', 'excludePostId');
Change the 66 to the ID of the post you want to exclude.
Is there something missing in this code? I tried it by adding it to my Generatpress Child Theme and cleared the cache but I didn't see any improvement.
Hi Caitriona,
What's the code you are using? Have you changed the 66 to the IDs of the posts?
Hi, yes I did. Sent you a screenshot.
The code looks right.
I checked all 27 pages of your blog, I don't see this post.
Did you try using the search bar? When I use the search bar I can see it. The search bar is in the top right when you click on Blog
That's the search result page, your original request is to remove the post from blog.
So do you want to remove the post from the search result page as well?
Ah ok. I didn't know there would be a difference. Yes, I would like it too, please.
Then use this snippet instead:
function excludePostId($query) {
$postIds = array(
4986
);
if ( ($query->is_home() ||$query->is_search() ) && $query->is_main_query() ) {
set_query_var('post__not_in', $postIds);
}
}
add_action('pre_get_posts', 'excludePostId');
Will this code remove from blog and search results? I need it removed from both. Or will I just use both snippets?
I have added it just now.
Only my snippet is needed, you can remove the old one.
Just checked the search result page, it seems working well:
https://www.screencast.com/t/IDEdVr9mjj
Thank you, Ying :)
No problem :)