0

Is it possible to show ONLY the first 300 words (or even 50 lines) of every blog post for anonymous users? Instead of show the whole article on the page? And after registration all the post would show.

Thanks!!!

2
1

It wasn't quite as easy as @Pat J made it sound, especially if you want HTML formatting with your copy. I cribbed from this answer and came up with the following code for you. I've tested it and it works:

    // If the user is logged in, display the full content
    if(is_user_logged_in()):
        the_content();
    else: // The user isn't logged in and should only see the first 300 words
        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );
    endif;

UPDATE

There are 2 errors in your code. One is the ; after the initial if statement, and the arrays don't match: $roles v $role.

The following code integrates the original answer (logged in/out) with your modifications (if is array):

    if(is_user_logged_in()): 
        if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): 
            the_content();
        else: 
            echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );
        endif; 
     else:
        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) );
     endif;

Good luck!

6
  • 1
    Hmm, I didn't realize wp_trim_words() strips all the tags out. Good catch. (I'd still recommend using the the_content filter for this; the code you've posted looks like it's meant to go in a template file.)
    – Pat J
    Sep 30 '21 at 2:41
  • @PatJ you mean in the else statement? When I used the_content() there it wouldn't trim words, it just blatted the whole thing.
    – Pixelsmith
    Sep 30 '21 at 4:37
  • 1
    Thank you! Your code works perfect! But in my case I'm editing the the_post() (theme folder) I had made some changes to your code; logged in users / 3 roles only. I put the following code, but i'm getting "critical error" message from wordpress. I'm sure it's a sintaxis error. ¿Could you help me? :-P
    – Arquera
    Oct 1 '21 at 15:27
  • 1
    @Pixelsmith I had made some changes to your code and no sixtaxs error. But it's not working for login users with other roles. This is the code: if(is_user_logged_in()): $current_user = wp_get_current_user(); $roles = $current_user->roles; if( in_array( 'administrator', $role ) || in_array( 'pmpro_role_2', $role ) || in_array( 'pmpro_role_1', $role )); while ( have_posts() ) : the_post(); (etc...)
    – Arquera
    Oct 1 '21 at 15:52
  • @Arquera absolutely. I'll have a look tonight and see what I can do.
    – Pixelsmith
    Oct 1 '21 at 17:04
0

You can use the excerpt to accomplish this, nonetheless the excerpt by default filter all HTML tags. To fix this, we need to filter and add new logic to it.

This will work filteryng the excerpt to change according to your needs:

You have to add this function in your theme's functions.php

functions.php

function wpse_allowedtags() {
    //The Tags you put here will not be removed, therefore if you want to include strong HTML tag, you should add it here as shown:
        return '<strong>'; 
    }

if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) : 

    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {
    $raw_excerpt = $wpse_excerpt;
        if ( '' == $wpse_excerpt ) {

            $wpse_excerpt = get_the_content('');
            $wpse_excerpt = strip_shortcodes( $wpse_excerpt );
            $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);
            $wpse_excerpt = str_replace(']]>', ']]&gt;', $wpse_excerpt);
            $wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */

            /*Set the excerpt word count and only break after sentence is complete.
            You can set this to any number you want in this case we'll use 300 
            words. */
                $excerpt_word_count = 300;
                $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 
                $tokens = array();
                $excerptOutput = '';
                $count = 0;

                // Divide the string into tokens; HTML tags, or words, followed by any whitespace in order to clean the not allowed HTML tags.
                preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $wpse_excerpt, $tokens);

                foreach ($tokens[0] as $token) { 

                    if ($count >= $excerpt_length && preg_match('/[\,\;\?\.\!]\s*$/uS', $token)) { 
                    // Limit reached, continue until , ; ? . or ! occur at the end
                        $excerptOutput .= trim($token);
                        break;
                    }

                    // Add words to complete sentence
                    $count++;

                    // Append what's left of the token
                    $excerptOutput .= $token;
                }

            $wpse_excerpt = trim(force_balance_tags($excerptOutput));

            if ( $count <  0) {   
                $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Reed more: %s &nbsp;&raquo;', 'wpse' ), get_the_title()) . '</a>'; 
               $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 
               $wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */
           }  
           $wpse_excerpt .= ' [...]';

            return $wpse_excerpt;   

        }
        return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);
    }

endif; 

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt'); 

After that, you only need to call the_excerpt to non registered users in the desired template file of your theme: (remember that it has been previously filtered to include 300 words)

 // The user is logged in, display the full content
    if(is_user_logged_in()){
       the_content();
     }else{
        // show the_excerpt
        <?php echo get_the_excerpt() ?>
     }
        

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.