I am Ad Taylor

Removing p tags from the_excerpt

short URL
http://www.iamadtaylor.com/?p=43

Shorts

This is a selection of hints, tips, finds and anything else I want to archive on the interwebs.

Why not just use twitter?

In part because I want to write a little more than 140 characters but mainly as I fear linkrot with much of what I tweet.

Removing p tags from the_excerpt

Making this blog I found many silly little stumbling blocks that slowed me down. Don’t get me wrong I think Wordpress is great but some of the formatting is simply awful.

A great example of this is the_excerpt call; There is a pretty good chance your going to want to link the text to post and if you care about semantics mark it up with hfeed and rel=”bookmark”. Well good luck if you want a strict valid page as it comes free wrapped in p tags.

RANT OVER. The fix: (Warning – this is a fix that goes straight for Wordpress core files)

  1. Open up wp-includes>formatting.php
  2. go to line 1498 (the function is called function wp_trim_excerpt($text))
  3. and add the line :
    // Removes the p from excerpts 
    remove_filter('the_excerpt', 'wpautop');

My function now looks like this:

function wp_trim_excerpt($text) {
	if ( '' == $text ) {
		$text = get_the_content('');

		$text = strip_shortcodes( $text );

		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
		$text = strip_tags($text);
		$excerpt_length = apply_filters('excerpt_length', 55);
		$words = explode(' ', $text, $excerpt_length + 1);
		if (count($words) > $excerpt_length) {
			array_pop($words);
			array_push($words, '[...]');
			$text = implode(' ', $words);
		}
		
		// Removes the p from excerpts 
		remove_filter('the_excerpt', 'wpautop');
		
	}
	return $text;
}

I’m not saying this is the correct way — I am by now means a developer — but it works.

EDIT : Since installing 2.8 I realised this was a bad idea as the modifications made were written over. I made a plugin to perform the action instead but I shall cover this in a post very soon.