Get limited text excerpts from a Wordpress post?

I use The Loop on my own webpage to get the last three posts from WP.

<?php
        $args = array( 'numberposts' => 3 );
        $myposts = get_posts( $args );
        foreach( $myposts as $post ) :  setup_postdata($post); ?>

                    <!-- DATE -->
                    <div class="date">
                    <?php the_time('m F Y');?>
                    </div>

                    <!-- TITLE -->
                    <div class="title">
                    <?php the_title(); ?>
                    </div>

                    <!-- SNIPPET -->
                    <div class="content">
                    <?php the_excerpt(); ?>
                    </div>
<?php endforeach; ?>

Everything is working fine - except the_excerpt(). I need about 15-20 words of plain text from the message to show it as a preview. How should I do it?

Thank:)

+5
source share
4 answers

You can try using something like this to capture the first 20 words of a message if there is no passage.

$content = get_the_content();
echo substr($content, 0, 20);
+4
source

Avoid using substr. Why?

If you use substr(), it may truncate HTML end tags and return invalid HTML.

Do not reinvent the wheel!

WordPress 3.3 wp_trim_words().

wp_trim_words Break Down:

wp_trim_words($text, $num_words, $more);

$text
    (string) (required) Text to trim
    Default: None

$num_words
    (integer) (optional) Number of words
    Default: 55

$more
    (string) (optional) What to append if $text needs to be trimmed.
    Default: '…'

:

<?php echo wp_trim_words(get_the_content(), 40, '...'); ?>

<?php echo wp_trim_words(get_the_excerpt(), 20, '... read more...'); ?>
+9

try the following:

The message contains images:

$content = get_the_content();
$content = apply_filters('the_content', $content);
$content = str_replace(']]>',']]&gt;', $content);
echo substr(strip_tags($content),0,100); 

and without images:

 $content = get_the_content();
 echo substr($content, 0, 25);
+2
source

Put this code in functions.php

function new_excerpt_length($length) {
  return 20;}
add_filter('excerpt_length', 'new_excerpt_length');

And just call this function from the template page or index.php file

the_excerpt();
0
source

All Articles