the_content filter – checking the post

I wanted to use the_content filter to check the post categories. If a post has certain categories selected, depending on the user I want to return a message saying something like ‘Sorry, you cannot view this’, rather than the content itself.

Having added the filter though, have discovered, the_content filter does not pass the post id or post into the function, so I cannot check the post to see if the conditions are met.

Can anyone suggest a way of doing this, without updating all the page templates?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’ll need to rely on the global post variable, or get_post(), which is essentially the same thing.

add_filter(
    'the_content',
    function( $content ) {
        $post = get_post();

        if ( in_the_loop() && has_category( 123, $post ) ) {
            // etc.
        }

        return $content;
    }
);

I included a check for in_the_loop(), because the the_content filter is commonly applied outside the loop in contexts where there won’t necessarily be a relevant global $post variable.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x