How to remove images (or selected HTML tags) from a WordPress page (and live happy)

no img tag on wordpressI love working with WordPress, there’s always a new tiny pretty trick around the corner that makes this great blogging tool behave just like something more versatile.

I’ve been working on a web site and the client asked for something that’s pretty against web usability and the usual SEO effort: she didn’t want to show any image or photo in any post on the home page, just the plain text but with full style and all other HTML tags while showing the full post, along with images, in single post page.

In a nutshell the order is: “no IMG tags in the home page posts”!

Besides being a weird idea, depriving every post of some sort of graphic appeal, this makes for quite a problem in WordPress realm.

Take the index.php main page, there’s already a WP function the_content() that shows the full-featured post.

There’s even a the_excerpt() function that shows the very first 50 chars of each post – although dropping each and every HTML tag and <br> line breaks as well.

Even a promising apply_filters() function proved unsuccessful in providing the right tag stripping.

The world’s not always black or white, so let’s enter the gray zone of WP with me!

After some research I came out with this solution:

  • use get_the_content() which return full untouched, unfiltered post content
  • use some simple regular expressions magic
  • show the resulting code

Here’s some code snippet from the index.php original page:

<div><?php the_content(__('View the rest of this entry...')); ?></div>

which became:

$content = get_the_content();
$postOutput = preg_replace('/]+./','', $content);
$postOutput = nl2br($postOutput);
echo $postOutput;

Problem solved: images are now displayed only on home page while retaining HTML tags correctly, images reappear on second-level pages as usual.

This simple technique may be applied to any HTML tag: my guess is that some tag-stripping may be useful for most bloggers on home pages as well as pages (not posts), since you can get rid of some rubbish right where you want it (e.g.: embed flash code, some banner code…).

Happy WordPress- ing!

This entry was posted in Design, Development, PHP, Programming, Widget, Wordpress and tagged , , , , . Bookmark the permalink.

Leave a Reply