You might have wanted to hide a WordPress page or blog post from the home page or blog archive. While you can make private, or even password-protected WordPress posts, however, sometimes when the user simply wants to hide the post from the WordPress homepage but still intend to allow some other viewers to view the post if they have a direct link. In such cases, you need to get somewhat technical and use some complex strategies.
In this article, we are going to present various ways to hide a blog post or page from the WordPress homepage, search results, category archives, and more.
WordPress provides you an option to set the visibility for your blog post or page by default. This visibility setting is present just beneath the “Publish” button.
This setting has 3 options to hide the posts or pages completely or partially:
You can hide multiple pages or posts by creating a category for those pages. Activate the plugin “Show IDs by Echo Plugins” to display the IDs of your categories, pages, and posts. Once you create the category for several pages or posts you want to hide and get the category ID, simply insert the code given below in your functions.php file of the theme. This code will hide all the pages or posts in the category so they will not appear on the homepage and blog page.
function exclude_category($query) {
if ( $query->is_home() ) {
$query->set( ‘cat’, ‘- Category ID’ );
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘exclude_category’ );
You can choose to hide your posts or pages from specific sections of the WordPress site including archive, blogroll, search results, etc. Keep reading to know these secret tricks:
function exclude_single_posts_archive($query) {
if ($query->is_archive() && $query->is_main_query()) {
$query->set(‘post__not_in’, array(1001, 1002,1003));
}
}
add_action(‘pre_get_posts’, ‘exclude_single_posts_archive’);
The numbers 1001, 1002, 1003 indicate IDs of pages or posts.
function exclude_single_posts_home($query) {
if ($query->is_home() && $query->is_main_query()) {
$query->set(‘post__not_in’, array(69489, 69177,68878,68736));
}
}
add_action(‘pre_get_posts’, ‘exclude_single_posts_home’);
function exclude_posts_pages_from_search( $query ) {
if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
$query->set( ‘post__not_in’, array(1001, 1002 ) );
}
add_action( ‘pre_get_posts’, ‘exclude_posts_pages_from_search’ );
function exclude_single_posts_feed($query) {
if ($query->is_feed() && $query->is_main_query()) {
$query->set(‘post__not_in’, array(69489, 69177,68878,68736));
}
}
add_action(‘pre_get_posts’, ‘exclude_single_posts_feed’);