Custom Excerpt to Handle Broken HTML

If you want to retain some HTML tags in your excerpts, you can’t just select the text from the content of the file.  Usually this will cause some HTML tags to be ‘broken’ because the ending tag is not included in the selected text.

Here is a function to be added to your functions.php file which will correct the HTML.

//custom excerpt
function custom_excerpt($num,$p = true,$echo=true) {
// $num is the number of 'words', space separated, to excerpt
// $p will enclose the excerpt in p tags if true
// $echo will echo the excerpt if true, return it if false
$theexcerpt = get_the_content();
$new_theexcerpt = explode(' ', $theexcerpt, $num);
$new_theexcerpt = implode(' ', $new_theexcerpt);
$new_theexcerpt .= '...';
libxml_use_internal_errors(true); //use this to prevent warning messages from displaying because of the bad HTML
$doc = new DOMDocument();
$goodHtml = $doc->saveHTML();
$cleanHtml = trim(ereg_replace('(.*)<body>(.*)</body>(.*)', '\2', $goodHtml));

if($p==true) { $cleanHtml = '<p>' . $cleanHtml . '</p>'; };
if ($echo != true) return $cleanHtml;
echo $cleanHtml;