Can't see post images in post descritptions

Dec 23, 2011 at 9:16 AM
Edited Dec 23, 2011 at 9:20 AM

I've set my blog settings to: "Only show description of posts". But it doesn't show the image from the post in the descritpion. It only shows text. Is there a way to show a thumbnail or regular image from the post in the description?

Coordinator
Dec 23, 2011 at 4:21 PM

Here is example of site.master.cs (code behind for your theme's master page). It shortens post to 320 chars (postLength = 320) and then looks for the first image in the post. If there is an image, it adds it to the shortened post with class "first-post-img" so you can set image size and style in the CSS. If there is no image inside post, it will add default image that you need to put in your theme's "images" folder as "sample.png". You need to replace "YOUR-THEME-NAME" in the code below with your real theme name.

 

using System;
using Resources;
using BlogEngine.Core;

public partial class StandardSite : System.Web.UI.MasterPage
{
    #region Constants and Fields

    static readonly string pic = string.Format("<img class=\"first-post-img\" src=\"{0}themes/YOUR-THEME-NAME/images/sample.png\" alt=\"\" />", Utils.RelativeWebRoot);

    static bool initialized;
    const int postLength = 320;

    #endregion

    protected override void OnInit(EventArgs e)
    {
        if(!initialized)
        {
            Post.Serving += PostServing;
            initialized = true;
        }
    }
 
  private static void PostServing(object sender, ServingEventArgs e)
  {
      if (e.Body.Contains("[more]"))
          return;

      if (e.Location == ServingLocation.PostList)
      {
          var post = (Post)sender;
          string moreLink = string.Format("<a class=\"more\" href=\"{0}#continue\">{1}</a>", post.RelativeLink, labels.more);

          e.Body = GetPostPicture(e) + GetPostExcerpt(e, moreLink);
      }
  }

  static string GetPostPicture(ServingEventArgs e)
  {
      if (e.Body.IndexOf("<img ") <= 0)
          return pic;

      var start = e.Body.IndexOf("<img");
      var stop = e.Body.IndexOf("/>");
      
      if (stop > 0 && stop > start)
      {
          var s = e.Body.Substring(start, stop - start + 2);

          e.Body = e.Body.Replace(s, "");

          return s.Replace("<img ", "<img class=\"first-post-img\" ");
      }

      return pic;
  }

  static string GetPostExcerpt(ServingEventArgs e, string moreLink)
  {
      e.Body = Utils.StripHtml(e.Body);

      if (e.Body.Length > postLength)
          return e.Body.Substring(0, postLength) + "... " + moreLink;

      return e.Body;
  }
}