0

I'm using the following function to load my content dynamically:

apply_filters('get_the_content', $content)

However, I would like to apply an excerpt to this method but the only way I know how to do it is this way:

$content = apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file ));

Is there a way to apply an excerpt with my function? Thoughts?

Best,

Jon

2

If you mean you would like to create an excerpt automatically from the post's content, you could use wp_trim_words.

$auto_excerpt =
      apply_filters( 'the_excerpt', wp_trim_words( $content, 30, "..." ) ); ?>

Where 30 is the number of words you wish the excerpt to be at most, and the ellipsis "..." is what will appear at the end should the content exceed the specified number of words. But I wouldn't recommend do it that way.

A Better Way To Do It

It would be better if you just use the built in WordPress function get_the_excerpt which checks to see if an excerpt is already defined by the post author (unless you don't want to do that), otherwise it trims the post's content automatically via wp_trim_excerpt

Here's how to use it in your page template

/* Apply the excerpt filter to ensure tags get stripped if being
   generated by wp_trim_excerpt */
$excerpt = apply_filters( 'the_excerpt', get_the_excerpt() );

Now, to control the behavior of the excerpt you can optionally add these to your functions.php

function wpse_102311_excerpt_more( $length ) {
    return "..."; /* Set desired more text here */
}
add_filter( 'excerpt_more', 'wpse_102311_excerpt_more', 99 );

function wpse_102311_excerpt_length( $length ) {
    return 30; /* Set the max excerpt length here */
}
add_filter( 'excerpt_length', 'wpse_102311_excerpt_length', 99 );

This method is also nice because it consistent styling of excerpts, as you only need to use native functions in your template but allows you to retain control over the length of the excerpt as well as the more text.

Hope this helps!

| improve this answer | |
  • Hi Xiroxas, Thanks for quick response. Is there a way to strip tags here? This doesn't work: $content = strip_tags($content, '<p><br/>'); – Jon Nixon Jun 8 '13 at 4:02
  • Please see my revised answer. I recommend that you use the get_the_excerpt() method above if you are retrieving the excerpt, as the filters should take out unnecessary tags. However, if you are trying to strip all tags for some reason, please note the the second argument of strip_tags is the tags to allow. – a web dev Jun 8 '13 at 4:08

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.