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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.