How can I only show certain posts?

I haven’t had time to test this, but you can probably do this with the the_content filter hook. This way you won’t have to insert this code into archive.php, category.php, tag.php, author.php and any other archive file depending on how your theme is structured.

In your theme’s functions.php file add the following:

function my_filter( $content ) {

    $categories = array(
        'news',
        'opinions',
        'sports',
        'other',
    );

    if ( in_category( $categories ) ) {
        if ( is_logged_in() ) {
            return $content;
        } else {
            $content="<p>Sorry, this post is only available to members</p>";
            return $content;
        }
    } else {
        return $content;
    }
}
add_filter( 'the_content', 'my_filter' );

So what this could should do is intercept the content of the post between when it’s pulled from the database and it’s displayed. Then it’s going to check and see if the post has one of the categories listed in the $categories array (NOTE: It’s best to use the category slug here in the array). Then it will see if the user is logged in.

If they are, then it will display the post. If they are not, then it will set the content to the message and then send that back in place of the post’s content.

If the user is logged in, or the post is not in any of those categories in the array, then it will return the post as normal.

NOTE: If you’re using the_excerpt() in your theme instead of the_content(), then simply change the hook in the add_filter() call to 'the_excerpt' and it should work.

Leave a Comment