Back to Tutorials

Creating excerpt with image

  • on 07/05/2011 (updated on 13/03/2014)
  • in wolf, howto.

Have you ever wondered is it possible to do it with WolfCMS? Well, it is, and it’s not a brain surgery!

For this to work you’ll need two additional plugins, Truncate, for cutting text and Image by Devi for auto-cropping and resizing of images. For image plugin, be sure to rename the folder to “image” (without quotes). After download, enable both plugins.

Excerpt intro

A side note: I’ve done this under “Articles” page and the code is related to it, but it shouldn’t be a problem to make it work under “homepage”.

Image and Truncate

For crop and resize we will use this code:

<?php if ($article->hasContent('img')){?>
<img class="left" src="<?php echo URL_PUBLIC; ?>wolfimage?src=<?php echo $article->content('img');?>&w=150&h=100" alt="<?php echo $article->title(); ?>" />
<?php } 
    else {
    echo (' ');
 } ?>

It basically checks to see if the article has page-part named “img” and sticks its content in the path. If it’s empty, just text will be shown. You can change the size of your “thumb” by changing numbers after “img” part &w=150&h=100.

Truncate, on the other hand, takes part of the article and cuts it by a defined number of characters. For this example I’ve used 150.

<?php 
	$myarticles = truncate($article->content(), 150, "");
	echo $myarticles; 
?>

All this combined with “foreach” loop:

<?php $last_articles = $this->children(array('limit'=>5, 'order'=>'page.created_on DESC')); ?>
<?php foreach ($last_articles as $article): ?>
<div class="entry">
<?php if ($article->hasContent('img')){?>
<img class="left" src="<?php echo URL_PUBLIC; ?>wolfimage?src=<?php echo $article->content('img');?>&w=150&h=100" alt="<?php echo $article->title(); ?>" />
<?php } 
	else {
	echo (' ');
} ?>
<h3><?php echo $article->link($article->title); ?></h3>
<?php 
	$myarticles = truncate($article->content(), 150, "");
	echo $myarticles; 
?>
</div>
<?php endforeach; ?>

And the end result should look similar to this:

Excerpt list of articles

For this to work properly, you’ll need some css magic. And for minimal effort, you can define class “left” and just add it to “img” selector:

.left { 
	float: left; 
	margin: 1.5em 1.5em 1.5em 0; 
	padding: 0; 
}

Usage

Of course, this code mean nothing if you don’t know how to use it, and that’s easy too. In few steps:

1. Upload your image somewhere in /public directory
2. Go to your article and open it
3. Create a page-part named “img” by clicking on the green plus icon

Create a page-part

4. Enter the path to your image, but without /public/ part, just something like: images/my-image.jpg

Adding image path

And that’s all folks!

Of course, you can and should play a bit with css to make it more attractive, after all this is pretty rough example. If I’ve forgotten something, or it’s unclear, use the comment section below.

blog comments powered by Disqus