How do dynamic page meta description via code behind

Ryan Nguyen asked on February 28, 2020 08:30

As the title, I want to dynamic replace page meta description from code behind.
From google I have this code

protected override void OnPreRender(EventArgs e)
    {
        Page.Title = "My title";
        Page.MetaDescription = "My replacement value";
    }

This code snippet work fine with page title but not meta description. It always create new meta description tag in the bottom of head tag, so the meta description tag will be duplicate.
Can any one help me on this?

Correct Answer

Brenden Kehren answered on February 28, 2020 22:09

I'd set this information via a macro then in the metadata of that page. Go to the page in question, click Properties > Metadata and update the metadata with the fields you want to dynamically display. Here's a post about this methodology.

Typically what we do is set the base metadata at the root of the site, then modify things down in the content tree as needed. For instance if you have a /Products section of your site you can set the metadata of this page to be something like (/Products/Smartphones/Google/Pixel-4-XL) to any of the field names for that page type.

{%ProductName%} by {%CurrentDocument.Parent.DocumentName%}

This would render something like "Pixel 4XL by Google | Website Name". You can do the same in the keywords and description.

Now I get you don't want to set this on every product page so what you can do is set it on the parent page. Assuming you have different page types like custom.brand and custom.product you can do a check at that "brand" level like so:

{% if(ClassName.ToLower() == "custom.product") { ProductName + " by " CurrentDocument.Parent.GetValue("BrandName") } else { DocumentName } %} | Website Name

I'd take an approach like this vs. creating a web part. If you need to use the webpart though you can do so using this code:

if (CurrentDocument != null)
{
    CMS.UIControls.ContentPage page = this.Page as CMS.UIControls.ContentPage;
    if (page != null)
    {
        page.PageTitle = "Title here";
        page.Description = "Description here";
        page.KeyWords = "Keywords here"; 
    }
}
1 votesVote for this answer Unmark Correct answer

Recent Answers


Brenden Kehren answered on February 28, 2020 15:54

Provide more information about your environment. Are you using MVC, Portal Engine or ASPX development. Where are you attempting to set this code?

0 votesVote for this answer Mark as a Correct answer

Ryan Nguyen answered on February 28, 2020 16:20

Hi, i’m using k11 portal engine mode. The code running inside a webpart

0 votesVote for this answer Mark as a Correct answer

Ryan Nguyen answered on March 2, 2020 02:25

@Brenden Kehren thank you, it works

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.