Kirk Liemohn is a Principal Software Engineer at ThreeWill. He has over 20 years of software development experience with most of that time spent in software consulting.
How to Add an Author / Byline to a Modern Page in SharePoint Online
I needed to add an author/byline to a modern page in SharePoint Online, this field shows up right under the title of the page:
I needed to do this via an automated process, so I thought I would just use a little CSOM or PnP code to make that happen. Well, it turned out to be a lot harder than I thought…
Things Got a Little Complicated
Working with Bo George, we determined that the Site Pages library does have a hidden “_AuthorByline” field. Setting that should be easy, right? Well, the code silently failed for me. I could try to set it, but it didn’t do anything. Then I noticed that the PnP ClientSidePage class has a pageHeader (ClientSidePageHeader class) that has AuthorByLine and AuthorByLineId properties. Yay! But setting them seemed to have no effect for me either. Boo!
Then Bo, in his infinite wisdom, told me to check out the LayoutWebpartsContent property of the page list item. That was the ticket. However, he left me some homework. It turns out this field has HTML and in that HTML is a div with a data-sp-controldata attribute. The value of that attribute is HTML encoded, so it needed to be decoded. Then that value has some JSON, which needs to be parsed. Once you parse that you can find that there is a properties object which has an authors array. If you set that authors array properly (to a JSON object representing a user) then you’re getting somewhere (for some reason this reminds me of the book “If You Give a Mouse a Cookie” I used to read to my kids).
After you set the value you have to put the JSON back into a string, HTML encode it, put it back into the HTML attribute, then save the HTML back to the LayoutWebpartsContent. Whew! You can skip this last set of steps if you just need to read the user out, but that wasn’t my goal.
Here is the Code
Since that was a lot more painful than settings an _AuthorByline or AuthorByLine property, I thought I might save others the trouble and provide the code:
And before you go, check out another blog post I wrote a while back on a related subject of Update SharePoint Online System Fields via CSOM.
Hopefully, it helps someone out. If there is an easier way that I somehow overlooked, please let me know using a comment below!