go41

function filter the_content replace image post_thumbnail

von Joern am 26. Okt. 2010 | Keine Kommentare

putting large images in some of my posts I was used to filter the content and strip off the image there.
in my single.php template I used to call the ‚large‘ thumbnail first and displayed the filtered content below like this:
Code:

<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('large', array('class' => 'photo' , 'alt' => get_the_title() , 'title' => get_the_title() )); ?>
</a>
<?php } ?>
<?php echo apply_filters('the_content', preg_replace('/<img ([^>]*)>/', '', get_the_content())); ?>

advantage is that you can place an add or something else between the image and the stripped content.
In one theme (on http://www.ezxplain.com/458/rihanna-fea … rd-lyrics/ ) I preferred to place the post_thumbnail just inside the content where the original image was preg_replace-d by nothing.
The code I use instead of the_content is now:
Code:

<?php $mypostimage = ''; if ( has_post_thumbnail() ) {
$mypostimage = get_the_post_thumbnail($page->ID, 'large', array('class' => 'photo' , 'alt' => get_the_title() , 'title' => get_the_title() ));
} ?>
<?php echo apply_filters('the_content', preg_replace('/<img ([^>]*)>/', $mypostimage, get_the_content())); ?>

So if a post has a thumbnail set it will show the large thumbnail here, with the modified img class ‚photo‘ and the posts title in the alt and title tag.
while writing this I think it would be wise to display the_content without filter if there is no post_thumbnail.
So let’s put an else statement if has_post_thumbnail is false, should work like this:

Code:

<?php if ( has_post_thumbnail() ) {
$mypostimage = get_the_post_thumbnail($page->ID, 'large', array('class' => 'photo' , 'alt' => get_the_title() , 'title' => get_the_title() ));
echo apply_filters('the_content', preg_replace('/<img ([^>]*)>/', $mypostimage, get_the_content())); // content with replaced img tag
} else {
the_content('Read the rest of this entry &raquo;'); } // the_content unfiltered ?>

On the site given above this works well and the generated thumbs are smaller in file size to save bandwidth
____________________
you find me on Google+, Twitter and Facebook

(von: master)

Sorry, no posts matched your criteria.

Autor:

Du findest mich auch auf Twitter und Facebook!

Schreibe einen Kommentar

Pflichtfelder sind mit * markiert.


Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.

weitere forum Beiträge: