[ACCEPTED]-Get a limited, text-only excerpt from a WordPress post?-foreach

Accepted answer
Score: 30

Avoid using substr(). Why?

substr() truncates based on character count, NOT 6 whole words, and the last word would most 5 likely be truncated. It could also truncate 4 the end HTML tag(s) and return malformed 3 HTML, screwing up the rest of your layout.

Don't re-invent the wheel!

WordPress 2 3.3 onwards has a new core function called 1 wp_trim_words()

Parameter breakdown:

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

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

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

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

Example usages:

<?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?>

<?php echo wp_trim_words(get_the_content(), 50, '... read more &gt;'); ?>
Score: 5

You could try using something like this 2 to grab the first 20 words of the post if 1 there is no excerpt available.

$content = get_the_content();
echo substr($content, 0, 20);
Score: 2

try this :

Post 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 1 images:

 $content = get_the_content();
 echo substr($content, 0, 25);
Score: 1

Put this code in functions.php

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

And just call 2 this function from your template page or 1 index.php file


More Related questions