Exclude Specific Posts From WordPress Website

When you create your hide_from_loop custom field, You will have to re-save your posts to update the custom field value in the database for this tutorial to work.

I had a need recently to exclude some unimportant posts from a WordPress powered website. The posts would still be accessible if directly accessed or linked to, but I didn’t want this low quality content to be included within the WordPress loop via archive pages, search results etc.

I could create a meta box in WordPress but as I always use Advanced custom fields, I’ll use this plugin to create a checkbox area for each post to optionally exclude a post from the website.

I created a simple true/false field with the name hide_from_loop.

Create custom field

Make sure to show the field group to all posts.

Then we have a nice meta box to hide any post from WordPress.

Exclude posts from WP_Query

Next we use the pre_get_posts hook to show any posts that have our hide_from_loop custom field set to false which is 0.

function hide_from_loop($query) 
   if (is_admin() || !$query->is_main_query()) // If is admin area or is not the main query being run...
      return; // ...stop function from running

   if (is_archive() || is_search() || is_home()) // If is archive, search, or home pages
      $query->set( 'posts_per_page', 7 ); // Setting how many posts to show
      $query->set('meta_key', 'hide_from_loop'); // Look for our hide_from_loop custom field
      $query->set('meta_value', '0'); // Only show posts that are unchecked
add_action( 'pre_get_posts', 'hide_from_loop', 1 ); // Hook into pre_get_posts

If this tutorial has helped you, I wouldn't say no to a coffee as a tip ☕️

Buy Me a Coffee at ko-fi.com

Leave a Reply

Your email address will not be published. Required fields are marked *