How to hide and content from auto-generated excerpts?

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 );
}

Leave a Comment