In our project, we had situation like we need set available page templates to the given web. Since we already deployed the solution on production environment and we are not going to create site again, for existing site we need to do manually and for new sites which will be created we used feature stapler.
So here we will discuss how to set available page layouts programmatically (We did this using custom feature receiver and associated our custom feature in feature stapler).
Setting the available page layout programmatically is little difficult than setting in site definition in Onet.xml file.
To set the available page layouts there is a method “SetAvailablePageLayouts()” of publishing web. This method takes one parameter which is array of “PageLayout” class.
So to set the available page layouts programmatically:
- Get the PublishingWeb of the web where we need to set / update the available page layouts since SetAvailablePageLayouts() is method of PublishingWeb as
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(currentWeb);
- Get all the available page layouts for the web (Just in case if we want all the existing set page layouts) and created instance of ArrayList class to add the layouts.
PageLayout layouts = pWeb.GetAvailablePageLayouts();
ArrayList pageLayoutList = new ArrayList();
- Now, since the we will required instance of “PageLayout” class, I get the all available page layouts for the site collection, loop through them and compare with my new page layout which I need to add to the web and added in array list as follows:
SPSite site = pWeb.Web.Site;
if (site != null)
PublishingSite publishingSite = new PublishingSite(site);
if (publishingSite != null)
PageLayoutCollection pageLayoutsCollection = publishingSite.GetPageLayouts(true);
foreach (PageLayout pl in pageLayoutsCollection)
if (pl.Name.Equals(mynewpagelayoutnamewhcihneedtobemadeavailablefortheweb, StringComparison.InvariantCultureIgnoreCase))
- Type cast the arraylist into array of PageLayout class and call the SetAvailablePageLayouts() of PublishingWeb
PageLayout newPls = (PageLayout)pageLayoutList.ToArray(typeof(PageLayout));
I hope this will be useful to you. In case if any queries, questions feel free to discuss.