Skip to main content

SharePoint 2010 Content Query for Blog Posts

I hope this post will help many of you feel comfortable with using the Content Query Web Part.

In this post I will walk you through the process of creating a content query web part and configuring it to show custom field types. I will also give details on how to use XSLT to stylize and format the data being pulled.

I will be using the following scenario as an example. Say that you had a site collection with a top level publishing site. This publishing site would display a the most recent blog posts from all blog sites within its own site collection.

To solve this problem we will use a Content Query Web Part and a customized ItemStyle.xsl using XSLT.

Please note that the “SharePoint Server Publishing Infrastructure” needs to be enabled at the site collection to display the content query web part.

Step 1: Add a Content Query Web Part to Page

  • Navigate to the site that you want the blog posts to show up and click on edit page.
  • Under Editing Tools in the Ribbon, Click on insert > Web Part
  • Under the Content Rollup Category Click on Content Query
  • Then Click on the Add Button
  • Now that you have a CQWP on the page edit the web part

image

  • Expand open the “Query” properties
  • Since we will be just showing blog post in this query choose the following
    • List Type: Posts
    • Content Type Group: List Content Types
    • Content Type: Post
  • You should get a result like the following.

image

  • Next we will configure the web part to pull in additional values from the blog posts.
    • Title – linked to post
    • Date – with standard formatting
    • Body – Rich text
    • Author
    • Number of Comments
    • Categories

Step 2: Configure Web Part

  • Click on web part arrow and choose “Export”
  • Save the .webpart file to your desktop
  • Edit the “Content_Query.webpart” file in Notepad
  • Search for "CommonViewFields”
  • Replace the default “<property name="CommonViewFields" type="string" />” with the following:

<property name="CommonViewFields" type="string">Title, Text;PublishedDate, DateTime;Body, RichHTML;Author, Text;NumComments, Lookup;PostCategory, Lookup;</property>

  • Here are the available Field Types that can be used
    • Text
    • Note
    • Number
    • Currency
    • Integer
    • Boolean
    • DateTime
    • Threading
    • Lookup
    • Choice
    • URL
    • Counter
    • RichHTML
    • Image
  • When creating your own there are a few rules.
    • First off you need to separate each custom field type by a semi colon (Ex: Title, Text;Editor, Text)
    • There cannot be a space after the semi colon
  • Save the .webpart file
  • Edit the page again and choose Inster Web Part
  • It’s a little hard to find but click on the Upload a Web Part and browse for the custom .webpart file.

image

  • Click on Upload
  • Now when you click on Insert webpart you will see a category of imported webparts.
  • Click on Add button.
  • Now you will not see a difference but now the webpart has been configured to display these custom columns.

Step 3: Configure ItemStyle.xsl

  • Click on View All Site Content > Style Library > XSL Style Sheets
  • Download the itemstyle.xsl file
  • Add the following to the top of the file

xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"

  • At the very bottom of the xsl file add the following template

  <xsl:template name="BlogPost" match="Row[@Style='BlogPost']" mode="itemstyle">
        <xsl:variable name="SafeLinkUrl">
            <xsl:call-template name="OuterTemplate.GetSafeLink">
                <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="DisplayTitle">
            <xsl:call-template name="OuterTemplate.GetTitle">
                <xsl:with-param name="Title" select="@Title"/>
                <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
            </xsl:call-template>
        </xsl:variable>
        <div class="custom_posttitle">
            <xsl:call-template name="OuterTemplate.CallPresenceStatusIconTemplate"/>
            <a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
              <xsl:if test="$ItemsHaveStreams = 'True'">
                <xsl:attribute name="onclick">
                  <xsl:value-of select="@OnClickForWebRendering"/>
                </xsl:attribute>
              </xsl:if>
              <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
                <xsl:attribute name="onclick">
                  <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
                </xsl:attribute>
              </xsl:if>
              <xsl:value-of select="$DisplayTitle"/>
            </a>
        </div>
    <xsl:variable name="StartDate">
        <xsl:value-of select="ddwrt:FormatDateTime(string(@PublishedDate), 1033, 'g')" />
    </xsl:variable>
    <div class="custom_date">
            <xsl:value-of select="$StartDate" />
    </div>
    <div class="custom_description">
            <xsl:value-of select="@Body" disable-output-escaping="yes" />
    </div>
    <div>
        <table class="custom_postdetails" border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td class="custom_author">
                        By: <xsl:value-of select="@Author" /> |
                </td>
                <td class="custom_comments">
                        Comments: <xsl:value-of select="@NumComments" /> |
                </td>
                <td class="custom_category">
                        Category: <xsl:value-of select="@PostCategory" />
                </td>
            </tr>
        </table>
    </div>
  </xsl:template>

  • Save the file and upload it to back up to the style library

Step 4: Apply Custom XSL style to content query

  • Modify the Content Query Web Part again
  • Expand open The Presentation Category
  • Choose the custom “BlogPost” style
  • Save the page and you should now see the blog post with the following data and format.

image

Here are the files so that you don’t have to go through the whole process. Happy SharePointing!

Comments

Hi Erik,
just a thing: with new CQWP of 2010 you should not need anymore to export your web part to enumerate the Commonviewfields; you can use slots (and you do not need anymore to know the field type and the internal name).
Isn't it? Thanks for you post,
Barbara
Sergey said…
Hi! good post!

I try to find how display rating control in the CQWP?

Can I display more than 4 columns?

Thanx in advance.
Sharepoint-WIZ said…
Awesome post! I was searching for this for quite some time. Thanks for sharing the knowledge.
Anonymous said…
After step 3, I get an error on the web part, saying it cannot display open in Designer. When I attemp to edit the webpart I get an error page, asking me to go to the web part page to make changes. If I put the old version of the xls file back I see the title of my post only in the web part.
Catharina said…
Thank you! That was very helpful!

When implementing the web part, and also when looking at your screen shot, there is nothing showing up ater 'comments' and/or 'categories' at the end of each post. Aren't the number of comments and the categories for each post going to show up there?
Sharepoint said…
Great webpart!

Why dont you put it on sale and earn some bucks. http://www.thesharepointmarket.com/submit-product/
and start earning!
Anonymous said…
After following all the steps you mentioned, i'm still getting the title only. I'm not getting the option of BlogPost in my styles section under presentation category. Is it not necessary to change the DataColumnRenames property in the webpart.
Plz help me out.
Kurt said…
I am having some issues. I have followed the instructions but when I go in to edit the web part once it is modified and added to the page I get an exception. I believe there is something wrong the the XSL file after it is modified.

Correlation ID: 5d29889e-041b-40cf-9dc0-bc46fedbf983

That is about all that I can find that is helpful.
Kurt said…
I figured out my previous issue however I am having an issue displaying the number of comments as well as the categories. From your screen shot it looks like you are having the same issue.
SVP said…
Great Post..Very helpful as I had to implement the same functionality. But the number of comments part did not work for me. It seems it is not fetching the number of comments for a post. I saw some other users having the same issue..Anyone was able to resolve it?
vpage1 said…
Quick question for you. I'm a novice SP user. Can I configure the webpart such that if no results are pulling, I can display a default message? I am using this for 'critical alerts' type of messaging. When there are no active alerts, I'd love the webpart to simply display "There are no active alerts at this time". How do I do that? Thanks in advance!
Anonymous said…
Brilliant. Exactly what I was looking for!
Anonymous said…
ok, what did I do wrong. Uploaded the edited file. Tryed to insert it and got an error:
Item has already been added. Key in dictionary: 'CommonViewFields' Key being added: 'CommonViewFields'
Tryed to reload the original file and still get the same error.
miket said…
I also am having the number of comments and category not working. and from the looks of your screenshot, it's not working for you either. any thoughts?
ClausK said…
Hi
Thanks for at great post.

Regarding the comments and category.
I can get it to work when I point the CQWP to one specifik list with posts.
The category however needs styling, but I guess that is fixable.
Claus
Anonymous said…
thanks. it helped.
Christian Stahl said…
Nice post Erik! I do also got an post about the CQWP & ItemStyle for news roll ups: http://chrisstahl.wordpress.com/2011/05/28/display-news-pages-with-cqwp-%e2%80%93-part-i/
ilya said…
Fantastic - just what i was looking for :)
Kirkland said…
Great post! Really helped me out! I ran into a small problem that I hope someone will help out with. For my user account, I have no problem seeing the latest blog post, but for other users they get an error:

Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.
Technical Tips said…
I think this is very useful for many SharePoint users.
Satish Nagpal said…
Hello,

I folled all the steps but not able to see "BlogPost" Style.Am I missing something.

Plseae, help
Satish Nagpal said…
Hello,

Thank You so much for this post. It's work like charm.

Could you please advice me that how can I make some cosmatic changes. Like I want Blog Title Should be in Bold, "Created By " should be in Different Colour.

Any idea??
Eric Zaluzec said…
Hey,

Followed all the steps and selected Item style: BlogPost and hit apply.

I recieved this message in my Content Query Blog Section:
--------------------------------
Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.


Correlation ID:cc5ae083-f6c7-4248-b8b7-f91187751bea
-----------------------------------

Any ideas why this is showing up and how to solve this problem?
Sami AlSayyed said…
What a great article! Its really helped me a lot.

But I have a question, I want the post link to open the post in a page not in default SharePoint Item Display Form, how can I do that?

Thank you so much.
Mike said…
This dosnt' seem to pull back anything in the comments field for me. I also noticed that the image you use in this blog is not showing any comments.

When I wire the list directly in the post list I can get back comments, but that is the only way. Any idea what might be causing this?
westerdaled said…
Hi

With reference to NonsoloSharePoint's comment.. Do I just need to append the ItemStyles.xsl with my additional fields. I am thinking I want my CQWPs to be easily maintained by anyone other than me.
Rich T said…
Hi Erik,

Is it possible to retrieve contact information from a Query, only as i am trying to retrieve an About Me field for an Employee Spotlight webpart and i am unable to do so. This works fine when working with Announcements and Blog Posts. Any ideas?

Thanks, Rich
Anonymous said…
Hi Erik,

I have followed the steps up to step 3.
I can not find Library style after clicking 'view all contnet site'? Do you know why?

Thanks.
Rob said…
Likewise here - no Style Library. Only Site Pages and Site Assets. This WP - with your article - promises to solve several presentation challenges for me. All I'm missing is a Style library. Is there another Site feature I need to turn on?
Rob said…
I see now... http://spserver/style%20Library/ gets you there.
Anonymous said…
I get an error after uploading this style sheet. When trying to edit the web part.

I've downloaded your web part and the style?
patricksender said…
thanks for sharing...this is what i needed ;-)
John said…
Hey.

I had the same problem with the Comments and Categories not appearing.

I found that if you do the following then you can get the items to appear.

1. Edit the Webpart
2. Go to the Presentation section
3. In the fields to display enter the column name for your category and comments in the PostCategory and NumComments fields

Hope this helps someone
doum said…
Work great (after some problems like "Unable to display this Web Part")

But I have some problems :
- impossible to get categories
- do you have a tip to limit the body size ? (xx first caracters for example) because if we have big posts, it breaks the layout
doum said…
I forgot something :
- the URL seems to be wrong, if I click on the post title I have a 404 error, page not found
Erik Swenson said…
Looks like my code got removed from the comments:

John,
Hopefully your comment about adding those fieldnames to the webpart will help doum with his issue with the comments.

Doum,
To limit the content area use the follwing: (Note the part about the substring and the 200 is the charictor limit

xsl:value-of select="substring(@Body, 0, 200)" disable-output-escaping="yes"
Anonymous said…
After editing the ItemStyle.xsl all CQWP displayed an error.

Had to add xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"

in the top element
Erik Swenson said…
Im confused with the last comment. In Step 3 it states that you need to add in the
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"

I also checked the attached file and that has it in there as well. Did you miss step 3 or am I missing something else?

Erik
Anonymous said…
Works like a charm! Thank you very much!
corisan said…
Hi Erik,

Thank you for this post - it is exactly what I have been looking for.

I used the files you provided and the CQWP works as designed except for one small issue. The CQWP loads properly for both site owners and site members; however, site visitors (those with read-only permissions) are getting the following error message:

Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.

Correlation ID:529cf9c3-6e3e-4ac8-862e-41fb5c1d7ef5


Any advice you can offer would be greatly appreciated,

Cori
Erik Swenson said…
Cori,

Did you make sure that the itemstyle file is checked in, published as a major version and also approved?
Anonymous said…
Thank you this is exactly what I needed, and your comments were so easy to follow!

Just a question (complete SharePoint styling novice here) - how do I get the title to display (use the same style attributes) that are in the post list we're pulling in from?
I am very interested in your post. It is very useful for me. Thanks for share this valuable post.
Anonymous said…
For SharePoint application developers who want to:

> Add any (sub)Site(s) all over the SiteCollection
> Query any Content Type(s)
> Add any Column(s) in no time
> Change style to any Layout without deploying anything

Here is a project on CodePlex: http://enhancedcqwp.codeplex.com/
Kathrine said…
Hello

Great post, but...

I followed all the steps, and it appears that I have the same issue as Satish Nagpal. I can not see the style under presentation. What am I missing? I downloaded your style and webpart.
Erik Swenson said…
Kathrine,
Did you make sure that your itemstyle.xsl file in the style library was published as a major version and also approved? Also check to see if it is stuck in a approval workflow in your site has one enabled...
Great post, Erik, and thanks for posting the files to SkyDrive! Much appreciated.
Anonymous said…
Thanks a lot dude! This was a big help and it saved me a great deal of time.I will link your site from my @ jtwebnet.com. I had done this back in 2009 and I hadn't done it in a while and I had no documentation and I didn't feel like looking for it on MSDN.

Joet
Thanks!
Susannah said…
Hi Erik! Looking forward to pulling blog entries into our publishing look. Two questions -- is there a way to limit this customization, so that it only affects selected CQWPs, and does your process here work for anonymous site visitors?

I know this is a two-year-old article; just thought I'd ask. Thanks!
Susannah said…
Nevermind on my comment above; my questions were answered as I stepped through the directions.

New question: How can I show posts and comments in the same CQWP?

Thanks!
Anonymous said…
this looks cool....however I can't seem to get it to work. Even with your files, and checked in/published and approved versions of the ItemStyle

After I get back to the page and try to edit to set the webpart to the xsl template SP throws error, while I have this stylesheet, I can't edit any CQWPs which is a weird red flag to me. Is there something that perhaps rings a bell with this?
Rambabu Sure said…
Could you please help me displaying latest blogs from all the users

Thanks
Ram
Anonymous said…
What are the Column names and groups for Comments and Category? I've tried everything...
stylobaidu said…
Hi Erik,
very nice code but how do i get a word count. i just want to show some few lines of my blog..yhnaks
Lucas Diniz said…
I see your webpart show the category, but there is a way to retrieve the link to the @PostCategory page?
Chris Czosnek said…
For anyone not being able to get the number of comments to show... try adjusting your query to the URL of the posts list in your blog (/blog/Lists/Posts). You'll then need to edit your web part and fill in the presentation fields to display.
Any chance you can explain the XSL files for a novice / beginner.... i want to show 4 things

Name, Text; Division, Text; Sub Division, Text; Address, Text;

How would the File need to look for this
Charlie Baker said…
Thank you so much.
I have one problem left... Everything works great, I can see "Created by:" and "Date:". But the related information doesnt display. It should be saying "Created By: Charles Baker" But my name is not appearing. Any ideas?
Thanks.
Spandan-dpn said…
Hi,
i tried your code but it neither shows me number comments, Author name, Published Date.
Also character limit is also not working.
Could you please tell me how could i resolve this issue?
Aj Berg said…
Hi Erik

Thanks for this post.

I have followed each step carefully and still get the Correlation ID error.

Yes = the xsl is checked in and published as major version.

Question: Our devs already have some customisations in the ItemStyle.xsl. Is it possible they were would be any conflicts that could cause this error? What might they be?
Aj Berg said…
EDIT:

Is it possible for any code conflicts that could cause this error?

I am an XML noob. Though fairly competent at picking things up.
Cory Swartz said…
Two points of clarification, particularly for those new to editing XSL:

First, make sure the xmlns:ddwrt code is within the tag at the top of the file.

Second, the long code snippet needs to be added to the end of the file BUT BEFORE the closing tag.

I was getting the "Unable to display this Web Part" error until I figured that out. It is a no-brainer type of user error now that I figured it out.

Hope that helps!
Simitt Desai said…
To display all the field values from the sub-sites, do the following...
1. Edit the Content Query Web Part.
2. Under "Content Query Tool Part" on the right, expand "Presentation"
3. Scroll down to the "Styles:" section.
4. Select "Group style:" as "Default", Select "Item style" as "BlogPost" (last item in the list at the bottom).

and voila, you will see the blog postings from the sub-sites if you have created blogs within them.
Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!!
Hadoop training
Shae said…
Hallelujah! Thank you!!! I have followed a ton of other tutorials on this and only this one works. Works in 2013 too.
drewidd l said…
Hi Can someone please explain the exact column name to put under presentation in the "NumComments" and PostCategory" fields?

I have tried - comments, # comments, NumComments;
Category, Categories, postCategory

None of them work. Do we need to add new site columns for Postcategory and NumComments?

drewidd l said…
ok so I pointed the query to the actual blog page - posts
used # Comments; and Category[Custom Column];

and it works.
So will this only be able to pull Blogs from one site?
Jamie Bray said…
Thanks had it up an running in minutes....wish I had discoved this page this morning instead of trying to do it myself :/
Jamie Bray said…
had the same problem as everyone else with the comments and category's. sorted it , follow these steps....

1.Edit web part in browser
2.expand query
3.select show all items from list - pick the posts list from your Blog.
4.scroll down and and in NumComments type-
# Comments;
5.In post Category type-
Category [Custom Columns];
6. Click OK
7.done!
Hope this helps someone :)
Erik Swenson said…
Jamie B. Is your fix to get the #of comments to display for SharePoint 2010 or SharePoint 2013?
Unknown said…
Thanks Jamie B., your approach finally worked for me. (I'm using 2013 on premis, by the way)
shafin kothia said…
excellent post.it is informative.
Khalil

shafin kothia said…
it was Informative Post,and Knowledgable also.

Rayyan
Information was good,i like your post.
Looking forward for more on this topic
Lahir
Rakesh Parval said…
Wooh this is very informative article. Thank you so much..!
Rakesh
Kiran Joshya said…
It is incredible and informative knowledge. Impressive.
Kiran
This article is very good.informative style.. brilliant piece of advice.
Manideep
Ziggy said…
every get a change to show the title of the blog post bolded and in a h1?
Sidra Ali said…

I don't know whether its fair me or if other people experiencing issues with your site.
It shows up like a percentage of the composed content inside your substance are running off the screen. Would somebody be able to else please remark and let me know whether this occurrence to them also? This could bumblebee an issue with my program on the grounds that I've had this happen awhile ago. Much thanks to you..
web development company uae
Thanks for Information Microsoft SharePoint is a Web application platform developed by Microsoft. The web tools which are designed for the purpose of non-technical users so they can easily Use them. SharePoint can be used to provide intranet portals, document and file management, collaboration, social networks, extranets, websites, enterprise search and business intelligence. It also offers system integration, process integration and workflow automation capabilities. Sharepoint Online Training
Alina Anastasia said…
Hi Erik,

Thank u for helpful tutorial, can I display more than 3 column ?

It's really helpful for me if you want advice me about this :)

link asphotportal
Hello, I can set the column order for some of the columns in my custom Content Type (document set) but some of the columns will not display in the order that I specify when creating a new item. Is there a trick to this?

Thanked By
SharePoint Tutorial
Unknown said…
Erik, almost 7 years after you posted this it's still super useful. Thank you so much! I've learned a lot from you already over the years but look forward to the UX best practice to follow in future as well! :-)
Riya R said…
I just read your blog and wanted to say that I have really enjoyed and reading your blog posts.Any way I’ll be subscribing to your feed and I hope you post again soon.
SharePoint jobs in Hyderabad
SharePoint jobs in Chennai
Unknown said…

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

Kruger National Park & Stand for Sale in Marloth Park

Popular posts from this blog

SharePoint 2010 Base CSS Classes

This will be the first of many SharePoint 2010 posts. I will be focusing on a few of the main CSS classes used for SharePoint 2010 Public Beta. As the product becomes more final there might be some changes to the class names but I will be sure to create a new post if that happens. This will be quite a lengthy but it should be helpful. The default CSS given below are just highlights of the full CSS attributes for that class.I will be using a basic team site as my base for the screenshots. Here is a basic structure of the main areas that I will cover.Ribbon RowTable Row Left Site Actions Navigate Up Edit Tab List Browse Page Table Row Right Give Feedback Welcome Menu WorkspaceBody Container Title Row Title Title Logo Title Text / BreadcrumbPage DescriptionSocial Data SeparatorI like It Tags/Notes Top Header 2/Top Links li Static-Selected li Static SearchHelpStatus Bar Container Main A…

How To: Hide Left Side Navigation on Home Page

I was recently asked: "How can I hide the side nav bar on the main homepage layout ?? I want to be able to use the side NAV with in the team site etc etc, but I don't want it on the front page.. " There are a couple of ways to do this in SharePoint 2010. If you are using a non-publishing site you can add a Content Editor Web Part to the page and add the following to the HTML Source.
<Style>
body #s4-leftpanel
{
display: none;
}
.s4-ca
{
margin-left: 0px;
}
</style>Basically the CSS above hides the left navigation Div, and then sets the content area to not have a left margin. Once you are done, simply modify the web part and hide it on the page. If you are using a publishing site for your homepage simply add the same styles specified above to a custom page layout. That way if you have a need for other pages that do not need the left side navigation you can re-use the page layout.

Small Calendar for SharePoint 2010 & 2013

First off I would like to apologize for the lack of posts. I have been really busy with my new role as the UX Design lead within Slalom Consulting Boston. I will share more about that in another post. In a previous post Create Really Small Calendar I showcased how to do this for SharePoint 2007. However the 2010 and 2013 calendar views have changed and therefore we cannot use the same method or CSS as 2007.SharePoint 2010 Small Calendar:
SharePoint 2013 Small Calendar:
See video below for a video walk through on how to create a small calendar for SharePoint 2010 and & SharePoint 2013 with just CSS.Per the video above here is the code that I referenced:2010 CSS link reference in Master Page:
<SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/smallcalendar.css %>" After="corev4.css" runat="server"/>2010 CSS:
/**** Small Calendar ***/
.ms-acal-item{height: 10px !important;}
.ms-acal-sdiv,
.ms-acal-mdiv,
.ms-…