Contribute to Docs Contribute to Docs

Access Archives and Posts

This tutorial explains how to access Archives and the corresponding Posts.

Getting an Archive using the IApi

Archive pages are just a special kind of page that are used for structuring posts, categories and tags. The page Id is the key that is referenced in the field BlogId on the posts.

Archive Pages are loaded the same way as normal pages through the IPageServicein the IApi. The post archive model is loaded from the IArchiveService and can be filtered on time period, category and tag.

Getting Post for an Archive using the IApi

All posts can be accessed from the PostService in the IApi using IApi.Posts. Each post has a foreign key BlogId that specifies which Archive Page it belongs to. You can access posts directly by calling the IPostService in the IApi

This will get all Posts from all Archive Pages.

var allPosts = api.Posts.GetAll<Piranha.Models.PostBase>();

This will get all Posts from a single Archive Page.

var archivePosts = api.Posts.GetAll<Piranha.Models.PostBase>(archivePageId);

Requesting Posts as PostBase (an abstract base class) will in fact get all Post types. You can filter the returned Post by the Post type:

// This gets all post types
var allPosts = api.Posts.GetAll<Piranha.Models.PostBase>();

// This gets all posts without regions & blocks
var smallPosts = api.Posts.GetAll<Piranha.Models.PostInfo>();

// This gets just a specific post type
var somePosts = api.Posts.GetAll<MySpecificPostType>();

Advanced queries with using the DbContext

If you need to do advanced queries you can query the DbContext directly by injecting Piranha.IDb into you class. If you're using cache it is recommended to select the Id of the posts and then retrieve them through the IApi as posts will be cached.

Here is an example for retrieving the ten latest Posts from all Archives:

var tenLatestPostsFromAllArchives = db.Posts
    .Where(p => p.Published >= DateTime.Now)
    .OrderByDescending(p => p.Published)
    .Select(p => p.Id)

var posts = new List<Piranha.Models.PostBase>();
foreach (var id in tenLatestPostsFromAllArchives)

Instead of Piranha.Models.PostBase you can as well take other types as mentioned above.

If you have full cache enabled, GetById will be cached and the posts will only be fetched from the database the first time. If you can't use caching you can also do more advanced queries to actually select the data using the DbContext and transform them using the ContentService.

Get Categories and Tags of Posts

Other frequently used data from Posts are Categories and Tags, e.g. to build a category list or a tag cloud. You'll need the StandardArchive.Id as an argument to the following IApi methods. In the Archive razor page you could the following:

var categories = await api.GetAllCategoriesAsync(WebApp.CurrentPage.Id);
var tags = await api.GetAllTagsAsync(WebApp.CurrentPage.Id);