fbpx

Hide Private Posts on WordPress Blog Page

If you are creating a WordPress theme or editing an existing theme and you’re seeing private posts in your blog feed, you’ve come to the right place. We don’t want no stinking private posts on our WordPress blog page! So, how the heck do we get rid of them.

Step 1: Make sure you’re using a Child Theme

If you are currently editing a theme that you developed or are editing a child theme, proceed to Step 2. However, if you’re editing a theme that you haven’t developed you need to create a child theme. This will preserve the changes that you make to it, otherwise, they will be lost forever if you ever decide to update your theme. Check out our post on creating a child theme.

Step 2: Find the Posts Page for your WordPress Website

Hover over appearance in your WordPress dashboard and click on Editor.

Then, select the theme that you wish to edit.

Then, find the Posts page, sometimes named home.php. This will typically lead you to opening up the template-parts directory and finding the content.php file (which is typically the file that contains the excerpt that is used on the WordPress blog page).

Step 3: Edit the Template-Parts/Content.php File

In order to prevent private posts from being shown in the WordPress blog page, we need to first get the page id. Do that with the following code:

$ID = get_the_id();

Then, you’re going to want to see if the current post is currently set to a private status. You can check a post’s status with the get_post_status function. We want to set it equal to a variable in order to use that variable later.

$class = get_post_status($ID) == 'private' ? 'hide' : '';

Then, we need to add a class to the article element holding our post excerpt. This class will be associated with display:none; if the post is private. In our case, we associated the hide class with display:none; in our CSS stylesheet. And, in order to add a class to the article element we had to tap into the post_class function. See the code below:

<article id="post-<?php the_ID(); ?>" <?php post_class($class); ?>>

That code adds the hide class if the post is private or adds an empty class if the post is public (making sure that public posts are displayed and private posts are hidden from view).

In full, the code that we added to the content.php page is listed below:

<?php
// add this to prevent private posts from showing up in the blog feed
$ID = get_the_id();
$class = get_post_status($ID) == 'private' ? 'hide' : '';
?>
<article id="post-<?php the_ID(); ?>" <?php post_class($class); ?>>

Leave a Reply

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