0

You know when using the_excerpt() and no "excerpt" is set on a post it automatically uses the first 50 words or so.

Is the same also possible when using get_the_excerpt()

For instance I'm using get_the_excerpt() like this …

$return .= sprintf('
                <li>
                    <div class="title"><a href="%1$s">%2$s</a><span class="goto">a</span></div>
                    <div class="project-description">%3$s</div>
                </li>',
                get_permalink( get_the_ID() ),
                get_the_title(),
                get_the_excerpt()
        );

However if no excerpt is set, the get_the_excerpt() function doesn't show a fallback (the first 50 or so words). Any idea how to make that work?

1 Answer 1

2

The function the_excerpt() is only a echo of the function get_the_excerpt():

function the_excerpt() {
    echo apply_filters('the_excerpt', get_the_excerpt());
}

If you like a fall back for no input the excerpt meta box, then create a text from the content - get_the_content(). You can use the core function wp_trim_words() for set the counter for words and easy to set a text from all content. A example:

$excerpt = get_the_content();
$excerpt = esc_attr( strip_tags( stripslashes( $excerpt ) ) );
$excerpt = wp_trim_words( $excerpt, $num_words = 55, $more = NULL );
4
  • thank you, but how do I use that in my sample code above. How is the_excerpt used if an excerpt is set, but the stripped/trimmed content used when no excerpt is set? What is the cleanes solution for that? Commented Feb 20, 2013 at 12:51
  • Write you a custom function, there check for the excerpt and if empty, then use my example. This custom function include in your sprintf().
    – bueltge
    Commented Feb 20, 2013 at 12:57
  • How do you check the excerpt is empty?
    – Ayyash
    Commented Aug 28, 2013 at 14:13
  • Use the function get_the_excerpt() , there have a return, no echo. A example $my_excerpt = get_the_excerpt(); if ( $my_excerpt != '' ) { // todo }
    – bueltge
    Commented Aug 29, 2013 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.