0

So I am pretty new to WordPress and as a learning exercise I am trying to create a membership plugin that will allow the site to restrict access to pages based on user type.

The first step I am doing is just trying to remove page content and display a "membership only area" message. At first I was going to try injecting JavaScript that would remove everything from <*div id="content">, but I was not sure if custom themes are required to use that div id.

I am now trying to use the filter the_content to rewrite the content. I can remove the content completely by not returning the content but then it just shows a "content not found" message. So I am now trying to re-write the array itself by doing $content['post_content'] = "Members only"; . Instead of changing the post_content it prints it to the screen twice.

I might be on the completely wrong path for what I am trying to do but still, how would I go about re-writing the $content array so that WordPress would display the fake content that I want it to display?

2

The the_content filter will work for this. This filter allows you to alter the output of the_content() and get_the_content():

add_filter( 'the_content', 'wpse_members_only', 20 );
function wpse_members_only( $content ) {
    // If user is not logged in, show restricted content message.
    // Change this conditional statement based on how you want to check for
    // membership status. I'd suggest using capabilites, e.g. current_user_can( $capability , $object_id );
    if ( ! is_user_logged_in() ) {
        $content = __( 'Sorry, this content is reserved for members only.', 'text-domain' );
    }

    return $content;
}
| improve this answer | |
  • That works. Thank you! I hit the checkmark but I do not know how to mark the question as answered. – Jeremy D Jan 19 '17 at 22:42
  • Thanks, Jeremy! Clicking the checkmark marks a question as answered. – Dave Romsey Jan 19 '17 at 22:43
  • Actually I have another question. Is there a way to do this that would do the same thing but get rid of custom post types that don't use the_content, say if it used a custom query? – Jeremy D Jan 19 '17 at 22:50
  • Not exactly sure what you mean, but perhaps you could add a check using get_post_type(). The the_content filter is not going to work if the content is coming from some other place though. Probably would be best to ask a new question and add the details about where the custom post type content is coming from and how it is displayed, etc. – Dave Romsey Jan 19 '17 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.