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

Anonymous said…
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
Unknown 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?
Unknown 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.
Anonymous 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.
Anonymous 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.
Unknown 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.
Anonymous 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.
Anonymous 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?
Patrick Sender 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...
Unknown said…
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?
Unknown 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
Anonymous said…
I see your webpart show the category, but there is a way to retrieve the link to the @PostCategory page?
Unknown 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.
Unknown said…
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
Unknown 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.
Dpnh 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?
Unknown 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?
Unknown 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.
Unknown 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!
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.
Shae said…
Hallelujah! Thank you!!! I have followed a ton of other tutorials on this and only this one works. Works in 2013 too.
Unknown 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?

Unknown 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?
Unknown said…
Thanks had it up an running in minutes....wish I had discoved this page this morning instead of trying to do it myself :/
Unknown 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)
Unknown said…
excellent post.it is informative.
Khalil

Unknown said…
It is incredible and informative knowledge. Impressive.
Kiran
Ziggy said…
every get a change to show the title of the blog post bolded and in a h1?
Unknown 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
Unknown said…
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
Unknown 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

Popular posts from this blog

How To: Create Hyperlink to Modal Pop-Up Form

I was asked by a client recently if there was a way to create a hyperlink to a New Item Form anywhere within a site but still get the rich experience of the Modal pop-up window that grays out the background. (Note this is for SharePoint 2010 Only…) I basically took the code directly from the “Add new item” and the “Add Document” link within the list view. What this allows you to do is simply add in the following code to any content editor web part, Master page, or Page Layout in any site collection and display the form to be filled out. The user will get the nice experience of the modal window and not have to navigate away from their current page. This could be used for example a feedback form that is included in the master page so whenever someone wants to give feedback it is always going back to a central list. The only that is required for you to know is the List ID and the site name. Full Code For a List Item: <a onclick="javascript:NewItem2(event, &quot

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 Row Table Row Left Site Actions Navigate Up Edit Tab List Browse Page Table Row Right Give Feedback Welcome Menu Workspace Body Container Title Row Title

SharePoint 2013 Responsive Table Columns

I have been wanting to write this one for a while now. It is really amazing how UX is really finding is way into everything that we use and interact with. From Custom applications both mobile and on a desktop to document management or large data visualizations. There is always room for better usability and new concepts. SharePoint lists and library functionality really has not changed much for the past 10 years... I remember back in 2003 when I saw the same table/grid based views of documents and list items that exists in SharePoint 2013. But now we can look at them in a whole new way! In this video blog you will see how to create a responsive CSS table so that when the browser size is reduced it will hide specific columns. However hiding data is not always the right thing to do. What if a user needed those columns to filter on or to use for comparison to another document? Well that is where the custom jQuery Column chooser comes in. It allows you to see what columns are displ