SharePoint: Programmatically Adding our Custom Web Part on Wiki Page

We have a requirement like whenever our one custom site is get created, on welcome page one of our custom web part should be added by default. Since our custom site is based on OOB team site template, welcome page of the site is wiki page.

So here I will discuss steps to add our custom web part on wiki page.

Here problem with Wiki page is we do not have web part zone so that we can’t directly add into given zone. Here on wiki page we have content field available and we need to put some mark up as the value of this field.

So written one web level feature and in feature activated added code


  1. Getting the web instance.
    1. SPWeb web = properties.Feature.Parent as SPWeb; 
  2. Get the welcome page.
    1. string welcomePageUrl = web.RootFolder.WelcomePage;  
    2. SPFile welcomePage = web.GetFile(welcomePageUrl); 
  3. Check out the welcome page.
    1. welcomePage.CheckOut(); // Here make sure that Check out type of welcome page //is none or checked out to current user then only check out the welcome page 
  4. Get the webpart manager as.
    1. SPLimitedWebPartManager wpmgr = welcomePage.GetLimitedWebPartManager(PersonalizationScope.Shared) // Use Using //for this in actual code 
  5. Create the instance of our custom webpart and add using webpartmanager.
    1. //Generate the id for the web part, this id is also used in markup which we  
    2. //will assign content field  
    4. Guid storageKey = Guid.NewGuid();  
    5. string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-''_'));  
    7. //My custom wp  
    8. MyCustomWp myCustomWP = new MyCustomWp();  
    9. myCustomWP.ID = wpId;  
    10. myCustomWP.ChromeType = PartChromeType.None;  
    11. myCustomWP.Title = “My Custom WP”;  
    13. wpmgr.AddWebPart(MyWorkspacesWP, "wpz", 0); 
  6. Set the MarkUp required to Content field for the wiki page.
    1. string markup = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>"new object[] { storageKey.ToString("D") });  
    3. //Get the list item to read the field  
    4. SPListItem item = welcomePage.Item;  
    6. //Wiki field  
    7. item[SPBuiltInFieldId.WikiField] = markup;  
    8. item.Update();  
    9. welcomePage.Update(); 
  7. Finally check in the page.
    1. welcomePage.CheckIn(string.Empty, SPCheckinType.MajorCheckIn); 

Enjoy SharePoint

Your comments/suggestions/feedback is most welcome!