Shiba

Adventures in WordPress

  • — Home —
  • Dog
  • Art
  • Contact
  • WordPress Articles
    • WP Plugins
    • WP Programming
    • WP Admin Panels
    • WP Theme Design
    • WP How-To
    • WP Theme Images
You are here: Home / WordPress Design / WordPress Excerpt – How to Style It

WordPress Excerpt – How to Style It

Tweet

by ShibaShake 36 Comments

WordPress Excerpt - How to Style It

WordPress excerpts are most useful when you need to display a series of posts in a single page. This often occurs in your –

  1. WordPress blog homepage – your most recent posts.
  2. Category page – All posts belonging to the selected category.
  3. Tag page – All the posts containing the selected tag.
  4. Archive page – All posts published during the selected date.
  5. Search results page – All posts and pages matching the search query.

You can set the maximum number of posts that are shown in these pages by going to Settings >> Reading and changing the number on the Blog pages show at most option.

When multiple posts are shown, it is easier for your readers to find what they want by only giving them a summary of each post rather than showing them the entire post. You can enable this post summary functionality by using the WordPress the_excerpt command.

Here is an example blog with styled WordPress excerpts.

Example blog with styled WordPress excerpts.

1. Enable WordPress Excerpts

This is something that may already be supported in your WordPress theme, but if not, you can enable WordPress excerpts by doing the following –

Go into the index.php file of your theme. Find the line that contains the WordPress command

the_content

.

For example, in the ‘default’ theme you have the lines below in the theme index.php file –

<div class="entry">
	<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>

Replace the line

<?php the_content('Read the rest of this entry &raquo;'); ?>

with the code below –

<?php 
    if (is_single() || is_page()) 
         the_content('Read the rest of this entry &raquo;');
    else {
         the_excerpt();
    }
?>

This will style your blog so that it only shows text summaries when there are multiple posts, but shows the entire document for single posts or single pages.

You can further change the length of your post summaries by following these WordPress codex instructions.

2. Add Background Images to Your WordPress Excerpt

You can pretty up your WordPress excerpts by adding in background images to the top, bottom, or side of each excerpt. This is done by adding a background image entry to certain standard WordPress classes.

The exact class names you need to use will be greatly dependent on your current WordPress theme. However, there are certain standards that are adhered to by most themes.

In particular, each post is usually encapsulated in a post class. If that post is an excerpt, it will further be encapsulated within an excerptcontent class.

.excerptcontent {
	background: url("side_graphic_URL.jpg") top center repeat-y; border: none; 
}	

.post {
	background: url("top_graphic_URL.jpg") 90% 0% no-repeat; border: none; 
}

Above, we set a side border graphic and a top background graphic for our excerpts. Just add the above styles into the style.css file of your current WordPress theme.

3. Add Thumbnail Images to Your WordPress Excerpt

To add thumbnail images to our WordPress excerpts, we need a function that extracts the first image from our posts. The get_first_image function below was obtained from the WordPress.org support forum.

function get_first_image() {
	global $post;
	$first_img = '';
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches [1] [0];

	return $first_img;
}

Just add this function to your theme functions.php file.

Next we need to call this function from our WordPress theme. Add the code below, right above the_excerpt command, in your theme index.php file.

?>
        <div class="alignright" style="margin:20px;">
             <a href="<?php the_permalink() ?>">
             <img src="<?php echo get_first_image();?>" width="200" height="200"/>
             </a>
       </div>
<?php

This adds a right-aligned image to each post excerpt, which we size at 200px by 200px. The code in your index.php file will now look like this –

<div class="entry">
<?php 
    if (is_single() || is_page()) 
         the_content('Read the rest of this entry &raquo;');
    else {
?>
        <div class="alignright" style="margin:20px;">
             <a href="<?php the_permalink() ?>">
             <img src="<?php echo get_first_image();?>" width="200" height="200"/>
             </a>
       </div>
<?php

         the_excerpt();
    }
?>
</div>

4. Resize the Images in Your WordPress Excerpt

However, the results are still not exactly what we want because the aspect ratio of the images are not maintained. This may make some images look stretched or compressed.

Here is a simple function to resize the image and maintain its aspect ratio. Add the code to your theme functions.php file. –

function url_exists($url) {
	$headers = wp_get_http_headers($url);
	
	if (!is_array($headers)) :
		return FALSE;
	elseif (isset($headers["content-type"]) && (strpos($headers["content-type"],"image") !== false)) :
		return TRUE;
	else :
		return FALSE;
	endif;
}

function resize_image($image, $alt, $newwidth, $newheight) {
	if (!file_exists($image) && !url_exists($image)) return '';
	list($width, $height, $type, $attr) = getimagesize($image);
	if (!$width || !$height) return '';

	if ($newwidth) 
		$newheight = intval($newwidth/$width * $height);
	else
		$newwidth = intval($newheight/$height * $width);
	return '<img src="' . $image . '" width=' . $newwidth . ' height='. $newheight . ' alt=' . $alt . '/>';
}
  • $image is the image file or url.
  • $alt is the alternate text to use.
  • $newWidth and $newHeight are the new width or height you want to resize the image to. Only one of these parameters will be used to resize the image. If $newWidth = 0 then $newHeight will be used to resize the image. Otherwise, $newWidth will be used.

The resize image function will return the HTML string for the input image, at the proper size. If the image cannot be found, a NULL string is returned.

Finally you just need to call this resize_image function from your theme. Replace the previous call to get_first_image in your index.php file with the code below.

?>
        <div class="alignright" style="margin:20px;">
           <a href="<?php the_permalink() ?>">
              <?php echo resize_image(get_first_image(), get_the_title(), 200, 0); ?>
           </a>
        </div>
<?php

Here is what the final index.php file looks like, instead of the original the_content command.

<?php 
    if (is_single() || is_page()) 
         the_content('Read the rest of this entry &raquo;');
    else {
		?>
        <div class="alignright" style="margin:20px;">
           <a href="<?php the_permalink() ?>">
              <?php echo resize_image(get_first_image(), get_the_title(), 200, 0); ?>
           </a>
        </div>
		<?php
         the_excerpt(); 
    }
?>		
WordPress Excerpt - How to Style It

Related Articles

Wordpress Search Widget - How to Style It

How to re-style the native WordPress search widget using CSS.

Style Your RSS Feeds in WordPress

How to display and style RSS feeds in WordPress.

Optimize Your WordPress Plugins with Tags

Shows how you can enhance page speed by using tags to selectively run plugins only when needed. Page speed is important because it affects Google Page Rank and user experience.

Comments

  1. James says

    July 2, 2018 at 11:03 am

    Great post. I really need some help. I have set border lines around my excerpts on my blog page/post page. The problem is my excerpts are touching the borderline on the left and the right. Could you please help me with some codes to set left and right paddings around my excerpt?

    Reply
  2. catherine says

    September 1, 2014 at 4:50 pm

    Thank you – excellent tutorial

    Reply
  3. Carlos Coelho says

    August 29, 2014 at 9:38 am

    Hi Shiba! First, congrats for your post, it’s very good and detailed.

    So, I have a problem with excerpt function and I’m newbie related to HTML/CSS/PHP/etc.

    I have excerpt in the front page featured pages (img1) and in which page I begin with a quote (img3) which I don’t want to appear in the front page. How do I remove it? Using a filter? Which? How?

    If you could help me I would be very thankful. I’m building this site as a gift for my parent who has an architecture company but doesn’t have money to pay for one web designer. It’s kinda surprise and I want the site to be good, pleasant and comfortable.

    If you want I can turn the website visible, just contact me by email!

    (img1 link) -> http://prntscr.com/4hopcw
    (img2 link) -> http://prntscr.com/4hoqlk

    Thanks!
    Carlos Coelho

    Reply
  4. CJ says

    May 25, 2014 at 11:33 am

    Cool tutorial. This helped me!

    Reply
  5. sunshine says

    January 29, 2014 at 7:33 am

    Thanks for your great tutorial!
    I did everything without point 2 and I have nothing with “excerpt” in my css-Style Sheet. (I use an old theme, but it looks nice)

    But I have two “problems” with it:
    1. My thumbnail is above my excerpt-text!
    2. I want, that my excerpt-text is with the html-tags from my article, if I have no excerpt written.

    Have you a tipp for these two “problems”?

    Reply
  6. Ask a Toddler says

    September 19, 2013 at 6:35 am

    Hi, Thank your very much for these clear instructions!

    I’ve tried very hard to code without success.

    What I’m trying to do is have the most recent post show in full and all others excerpt with thumbnail exactly like what you see here: http://www.theminimalists.com/

    My website is askatoddler.com

    Thank you very much for your help.

    Peter

    p.s. I love dogs! Here’s Jack: askatoddler.com/about/

    Reply
  7. Maya says

    July 31, 2013 at 11:05 pm

    Very good job, thank you! But if there is not an image in the post? Could you rewrite the code to get any default image in this case, please!

    Reply
  8. Mat Wigley says

    December 3, 2012 at 4:37 am

    Hi, I’m using your backgrounds plugin here:
    http://www.matwigley.co.uk/mel
    and I can’t work out how to style the ‘archives’ section, the background image doesnt’t appear.

    I’m also using the PagesPosts plugin on this site. Do you think it may be causing a clash?
    Thanks, great plugin.

    Reply
    • ShibaShake says

      December 4, 2012 at 10:45 am

      Hmmm, I can’t seem to get to your archive page. Send me a link and I will have a look.

      Reply
  9. pier says

    November 23, 2012 at 3:55 pm

    hi, i need a beautiful, eye-catching style for the comments on my forum,
    just the style, not any programming code, any suggestion??

    Reply
  10. Vorhins says

    November 4, 2012 at 3:44 pm

    Thanks first.

    Unfortunately I get following alert on my side.

    Warning: getimagesize() [function.getimagesize]: URL file-access is disabled in the server configuration in /kunden/376743_12055/webseiten/wp-content/themes/twentytwelve/functions.php on line 464

    Do you know what I did wrong? It must have something to do with the Resize.

    Reply
    • ShibaShake says

      November 5, 2012 at 7:31 am

      getimagesize() is a PHP function that is sometimes disabled on the server side for extra security. It sounds like that is the case in your server configuration.
      http://php.net/manual/en/function.getimagesize.php

      This is an older post that I wrote for the old WordPress default theme. I really should update the post, but there is never enough hours in a day. In new themes, I would just use the Featured Image capability.
      http://codex.wordpress.org/Post_Thumbnails

      Reply
  11. FJC says

    October 26, 2012 at 10:38 am

    Awesome! Thanks!!

    Reply
  12. mark shirley says

    July 28, 2012 at 10:46 am

    Hi is there an updated version that uses twentyelevens theme files. or if you know of another tutorial could you point mt to it – thanks mark

    Reply
    • ShibaShake says

      August 1, 2012 at 7:10 am

      Hello Mark,
      I have not seen a tutorial for Twenty Eleven, but I looked for this information a long time ago.

      Reply
  13. Marian says

    March 8, 2012 at 2:26 am

    nice work…
    is it possible that the images will be cropped and not being resized?
    greets

    Reply
    • ShibaShake says

      March 8, 2012 at 3:43 pm

      For proper cropping you can set image sizes by going to Settings >> Media.

      You can also add additional sizes through PHP.
      http://shibashake.com/wordpress-theme/wordpress-image-size

      Reply
  14. Daniel M says

    December 9, 2011 at 7:03 am

    Hi thanks for the guide you took time to write, I’d like to know how I can change the height of the excerpt??

    Reply
  15. ben says

    August 16, 2011 at 4:25 pm

    Hi im just trying to figure out how to remove a “read more” button on specific exeprts, only the ones I choose. any ideas? how do i make the read more dissapear on short exepts?

    Reply
    • ShibaShake says

      August 16, 2011 at 4:32 pm

      You can use the excerpt_more filter –
      http://codex.wordpress.org/Template_Tags/the_excerpt#Only_in_version_2.9_and_higher_of_WordPress

      Reply
  16. Kristo says

    April 1, 2011 at 1:01 pm

    Hi, thanks for the nice “Add thumbnail images” function. I found it to be useful.
    However, I’m not so sure about necessity of the “resize_image” function. Firstly – it made the page loading much slower, secondly – why not use only the “width” parameter in the image tag (without “height” parameter)?
    It resizes images proportionally and doesn’t need any additional functions…

    Reply
    • ShibaShake says

      April 2, 2011 at 12:22 pm

      Hello Kristo,
      I wrote this tutorial some time ago so I don’t remember the exact context. I think it may have to do with browser and theme compatibility. Specifying just one of the parameters, I think, did not work on some of the older browsers or some of the WordPress themes I was experimenting with. In particular, if the img height is pre-specified in CSS, it may not be overridden.

      This is my best guess anyway 🙂 For newer installs I would just use the standard WordPress thumbnail feature that shipped with 2.9.

      Reply
  17. Mark Divers says

    February 4, 2011 at 1:12 am

    I tried the “Add Thumbnail Images to Your WordPress Excerpt” but could not get it to work. I could not find anything in index.php that said
    , but I could in the loop.php file. It occurs in a few places in that file. Hee is the sumary page I want to add thumnails to…

    http://randdesertmuseum.com/site/category/johannesburg/johannesburg-mills/

    Thanks for any help you can give me! I started with the Twenty Ten theme, this may be the problem.

    Mark Divers

    Reply
    • ShibaShake says

      February 5, 2011 at 8:57 am

      Hello Mark,
      Yeah when I wrote this article, the Default theme was still Kubrick, I should update it at some point.

      I just visited the page above and saw that you have added thumbnails to it. Glad you found a solution.

      Reply
  18. Monty says

    November 19, 2010 at 10:56 am

    Hi,

    It’s superb, thanx a million!!!

    Only problem is that the div exists in the excerpt even if there’s no image. Is it possible to remove that alignleft div, cause it’s giving space before text cuz I’m using margins for it?

    thanx

    Reply
    • ShibaShake says

      November 23, 2010 at 8:22 pm

      Yeah sure just test for the image before rendering the div. Something like this –

      $image = get_first_image();
      if ($image) :
      	?>
              <div class="alignright" style="margin:20px;">
                 <a href="< ?php the_permalink() ? rel="nofollow">">
                    < ?php echo resize_image($image, get_the_title(), 200, 0); ?>
                 </a>
              </div>
      	< ?php
      endif;
      
      Reply
  19. Pascal says

    October 5, 2010 at 8:17 am

    Great tutorial. Works fine but at the end of the text I get […] instead of a link and the word “More”. How can I fix that? Thanks a lot.

    Reply
    • ShibaShake says

      October 5, 2010 at 8:43 am

      Try hooking into the excerpt_more filter.

      http://codex.wordpress.org/Plugin_API/Filter_Reference/excerpt_more

      Reply
  20. James says

    February 27, 2010 at 8:51 pm

    How about styling fonts, paragraphs etc? Excerpt command seems to strip all formatting. I don’t want to use another plugin because I’m already using “Thumbnail for Excerpts” to include a thumbnail.
    Is there some shortcode I can use

    Thanks

    Reply
    • ShibaShake says

      March 1, 2010 at 10:53 pm

      If you just want to style the fonts of the excerpt, then CSS is probably the easiest way to go. Just override the font style using CSS in your child theme style.css or functions.php file.

      Here is an article on child-themes –
      http://www.shibashake.com/wordpress-theme/customize-your-wordpress-blog-with-child-themes

      If you want to operate on the original excerpt data, you can just extract the raw information from the database ($post->post_excerpt or $post->post_content) and then process that.

      There are also WordPress filters (e.g. the_excerpt or get_the_excerpt) that allow you to insert your own excerpt processing functions.

      Reply
  21. Matthew says

    January 31, 2010 at 6:35 pm

    Is there a way to modify this so that it calls for the thumbnail version of the first image, instead of simply resizing the image?

    Reply
    • ShibaShake says

      February 1, 2010 at 10:11 pm

      Hi Matthew,
      You have very good timing. I just published a thumbnail plugin that does just that. The plugin uses the WordPress 2.9 post thumbnail system.

      http://www.shibashake.com/wordpress-theme/shiba-thumbnail-plugin

      Let me know if you have more questions.

      Reply
  22. ShibaShake says

    November 26, 2009 at 11:51 am

    It will work for any size image and it always preserves the image aspect ratio.

    If you enter in a width, it will size the image according to the width, if you set the width to 0, it will size the image according to the height.

    Reply
  23. Chad says

    November 26, 2009 at 10:52 am

    Does the resizing function only work for square images or can I resize an image to width:300px and height:200px

    Reply

Leave a Reply Cancel reply

Your email address will not be published.

Recent Posts

  • Screen-shot of mobile responsive Poll Daddy object, where text floats properly to the right of radio buttons.How to Make Poll Daddy Objects Mobile Responsive
  • Screen-shot of blog post with no page border (flowing design).Genesis Skins 1.5
  • Screen-shot of the media manager Create-Gallery screen, while doing a post search.Shiba Media Library 3.7
  • Screenshot of the Edit Gallery screen after we hit the Create Gallery button.How to Expand the WordPress Media Manager Interface
  • Blonde girl looking through and holding a circular picture frame.Shiba Gallery 4.3
  • Close-up of beautiful blonde holding a square picture frame.Google Authorship - Good or Bad for Search Traffic?
  • Shiba Widgets 2.0
  • Media Temple screenshot of editing my sub-domain DNS entry.Using CDN Cnames with w3tc and MultiSite
  • Shiba Skins WordPress ThemeShiba Skins WordPress Theme
  • How to add the Media Manager Menu to the Theme Preview InterfaceHow to Add the Media Manager Menu to the Theme Preview Interface

Recent Comments

  • WordPress Search Widget – How to Style It (56)
    • Nelson
      - Tanks master - Fine
    • TelFiRE
      - How do you style the "X" that shows up when you start typing?
  • Update custom inputs with the proper data using Javascript.Expand the WordPress Quick Edit Menu (58)
    • Mike G
      - This is exactly what is happening to me. It is updating the value in the database and in the column, but I have to refresh ...
    • PhoenixJP
      - Thanks for this tutorial. Does someone knows if this still work with wordpress 5.03 and 5.1.
    • Francine Carrel
      - This is a very long time away from your original comment, but did you ever work it out? I am stuck on the exact same thing ...
  • Custom meta-box with a set of radio-buttons.Add a Metabox to Your Custom Post Type Screen (27)
    • mike
      - Hi Shiba am a newbie to wordpress, I just installed a plugin with a custom post type, but has no option for discussion and ...
  • Write a Plugin for WordPress Multi-Site (45)
    • Andrew
      - Hi,action 'wpmu_new_blog' has been deprecated. Use ‘wp_insert_site’ instead.
  • Populate our Edit Gallery menu using a gallery shortcode.How to Add the WordPress 3.5 Media Manager Interface – Part 2 (29)
    • Janine
      - Still relevant in 2019.
  • WordPress Excerpt – How to Style It (36)
    • James
      - Great post. I really need some help. I have set border lines around my excerpts on my blog page/post page. The problem is ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (123)
    • Darshan Saroya
      - Update permalinks. Go to settings > permalink and just save it.

Copyright © 2021 · Genesis Skins by ShibaShake · Terms of Service · Privacy Policy ·