The Excerpt Reloaded: Another Reason Why Tags Aren’t Getting Closed
Update 7/17/2007: New version R1.4: Fixed the plugin URI and author URI so that the links on the plugin administration page will work.
Miriam of WordPress Garage commented that my first update to the_excerpt Reloaded did not fix an issue she was having at her site. I found the root cause of her problem and have a fix for this issue. I have updated my fix to the plugin, and you may download it from the box at the top of this article (and also from the download link in my original post).
Since the_excerpt Reloaded only takes the first N words of your post to create an excerpt, there is a chance that it may cut off your excerpt at a point where a tag within the excerpt doesn’t get closed. The input parameter, $fix_tags, to the_excerpt_reloaded() function is supposed to force the plugin to close any tags that this has happened to, but this doesn’t happen and tags remain unclosed. As a result of this your generated web page will not be valid XHTML.
Why It Happens
There are actually 2 reasons for this problem, and they are both caused by this PHP statement:
$output = $fix_tags ? $output : balanceTags($output);
The first issue is that the logic is reversed. If $fix_tags is true, we want the balanceTags() function to be called, therefore balanceTags() should appear right after the “?”, and not after the “:”.
The second issue is a result of the first statement inside the balanceTags() function, which is this:
if ( !$force && get_option('use_balanceTags') == 0 ) return $text;
What this means is that if $force is not TRUE, and the option “use_balanceTags” is not set, then the rest of the balanceTags code won’t be called, and the function will return what it was given without closing unclosed tags. Therefore, if your blog doesn’t meet these conditions, the function won’t close your unclosed tags.
The balanceTags() function takes $force as a second parameter. If it is omitted, it defaults to false. Therefore, if we want to force the tags to be balanced, we can set it to true as the second parameter in the call to balanceTags().
We also need to reverse the logic of the original conditional statement if we want $fix_tags to operate the way we want ($fix_tags==1 means we want to fix the tags, not $fix_tags==0).
Therefore, we need to change this statement:
$output = ($fix_tags) ? $output : balanceTags($output);
$output = ($fix_tags) ? balanceTags($output,true) : $output;
This fix is included in the plugin download at the top of this article (and also in my original article).
It was another fun time to find the reason for this problem. Thank you Miriam for motivating me to solve this puzzle.