Halloween Sale 15% off Ends in See the plans
PHP

Members-Only Category With a Teaser

Posts in a chosen category show visitors the first few lines followed by a log-in or sign-up box; logged-in members see the full post.

Don’t have WPIDE yet? Install it on your site

Code

// Category slug that holds members-only posts, and how many words visitors see.
$wpide_members_category = 'members';
$wpide_teaser_words     = 60;

add_filter( 'the_content', function ( $content ) use ( $wpide_members_category, $wpide_teaser_words ) {
    if ( is_user_logged_in() || ! in_the_loop() || ! has_category( $wpide_members_category ) ) {
        return $content;
    }

    $teaser = wp_trim_words( wp_strip_all_tags( strip_shortcodes( get_post_field( 'post_content', get_the_ID() ) ) ), $wpide_teaser_words );
    $box    = '<div class="wpide-teaser-box" style="border:1px solid currentColor;padding:1em 1.25em;margin-top:1.5em;border-radius:6px">'
        . '<p><strong>Keep reading with a free membership.</strong></p><p><a href="' . esc_url( wp_login_url( get_permalink() ) ) . '">Log in</a>';

    if ( get_option( 'users_can_register' ) ) {
        $box .= ' · <a href="' . esc_url( wp_registration_url() ) . '">Create an account</a>';
    }

    return '<p>' . esc_html( $teaser ) . '</p>' . $box . '</p></div>';
}, 1 );

add_filter( 'the_content_feed', function ( $content ) use ( $wpide_members_category ) {
    return has_category( $wpide_members_category ) ? '<p>' . esc_html( get_the_excerpt() ) . '</p>' : $content;
} );

Notes

Set the category slug and teaser length at the top. The teaser is plain text, so images and embeds in the hidden part are never sent to visitors.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.