0

Auto-generated excerpts just take the first x characters from the post content and cut that off at a certain point.

When there is a table or pre element in that part, the excerpt looks rather useless most of the time. How can I hide the content of these elements from my auto-excerpts?

  • Or, better yet: just use a user-defined excerpt. Why user-defined excerpts remain such an underused feature, I have no idea... – Chip Bennett Apr 22 '13 at 19:49
  • @ChipBennett I forget that often. And for pages there is by default no excerpt box, but an excerpt can happen in search results. – fuxia Apr 22 '13 at 19:50
  • Search results is an interesting edge case. I would recommend either enabling Excerpts for pages, or else customizing search.php and changing the loop output conditionally based on post type. – Chip Bennett Apr 22 '13 at 19:52
  • @ChipBennett Yes, you can do that for pages. Custom post types on the other hand are … unpredictable. – fuxia Apr 22 '13 at 19:53
  • Ideally, whatever registers the CPT would filter search results index query output via pre_get_posts. :) (Thus concludes my Pollyanna-ish view of WordPress development for today.) – Chip Bennett Apr 22 '13 at 19:55
2

To filter the content only when an auto-excerpt is generated you have to chain the hooks:

  1. Hook into get_the_excerpt and register a filter for the_content.
  2. In the second filter remove both elements and their content before the excerpt can see it.

Sample:

add_filter( 'get_the_excerpt', 't5_excerpt_clean_up', 1 );

/**
 * Register handler for auto-generated excerpt.
 *
 * @wp-hook get_the_excerpt
 * @param   string $excerpt
 * @return  string
 */
function t5_excerpt_clean_up( $excerpt )
{
    if ( ! empty ( $excerpt ) )
        return $excerpt;

    add_filter( 'the_content', 't5_excerpt_content' );

    return $excerpt;
}
/**
 * Strip parts from auto-generated excerpt.
 *
 * @wp-hook the_content
 * @param   string $content
 * @return  string
 */
function t5_excerpt_content( $content )
{
    // Remove immediately; maybe the next post doesn't 
    // use an excerpt, but the full content.
    remove_filter( current_filter(), __FUNCTION__ );

    // Fails with nested tables. Just don't do that. :)    
    return preg_replace( '~<(pre|table).*</\1>~ms', '', $content );
}

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.