27 Oct, 2009
Striping IMG tags from the_content in WordPress (and how to fudge page excerpts)
Posted by: Jennifer In: WordPress|WordPress Hacks|WordPress: Lessons Learned
Background: For a site I was working on, I was pulling in content from another page onto the homepage. However I wanted to just bring in an excerpt not the whole page. (And actually, a customized excerpt at that – not a default set character or word limit). I also didn't want any images brought in – I just wanted the text and any associated formatting.
Well, one problem here is that WordPress pages (at least as of this writing – with WordPress in version 2.8.5) do not have excerpts for pages. Only for posts. The way around this is to use the <!-- more --> tag where you want your break. So that works fine – but what about stripping out the images? I'm still working on my reg-ex knowledge, but I found this one from here and it worked for me. So this is what I'm doing when I'm pulling in my page excerpt:
<?php
$posts = query_posts('page_id=1234');
if (have_posts()) : while (have_posts()) : the_post();
//this makes the more work...
global $more; $more = 0;
?>
<h1><?php the_title(); ?></h1>
<?php
$content = get_the_content('');
$content = preg_replace('/<img[^>]+>/is', '', $content);
echo $content;
?>
<p><a href="<?php the_permalink(1234); ?>"><img src="/images/more.gif" /></a></p>
<?php endwhile; endif; ?>
*we're assuming "1234" is the ID of my page in the example above…
You'll also notice I manually added my "more" button image…
To read more about the more tag (and see where I got that global $more; $more = 0; from, you can see the WordPress codex here on the subject. (Scroll to the very bottom of the page – to the section title "How to use Read More in Pages")