Adding Social Meta Tags in Orchard

Your customer wants to boost their search engine results, so they ask you to add social media meta tags, for facebook, twitter and others.

In Orchard there is no ideal module for that. I have some ideas but not the time to make it, so here is a simple solution that you can apply without custom module.

Wrappers

In Orchard you can wrap any shape using wrappers. As their name suggests it will let you wrap a shape content and do stuff before and after this content.

In our case let's say we have a blog, and each blog post should also render some meta tags when it is rendered. The technique is to wrap any BlogPost content item with some wrapper that will include the correct meta tags, then render the content item as is.

Placement

Placement can be used to alter the rendered shapes based on specific rules. One of the possible alterations is to define a wrapper. Here is how you can wrap a Parts_Title shape from your Placement.info file:

<Match ContentType="BlogPost" DisplayType="Detail">
  <Place Parts_Title="wrapper=Wrapper__BlogPost;Header:5" />
</Match>

What it means is that when a BlogPost content item is rendered in Detail mode, we alter the placement of the Parts_Title shape by wrapping it in a new Wrapper__BlogPost one.

Wrapper-BlogPost.cshtml

Then we just need to create a Wrapper-BlogPost.cshtml file in the theme with this content:

@using Orchard.ContentManagement
@using Orchard.Mvc.Extensions

@{
  SetMeta("og:title", Html.ItemDisplayText((IContent)Model.ContentItem).ToString());
  SetMeta("og:url", Url.MakeAbsolute(Url.ItemDisplayUrl((IContent)Model.ContentItem)));
  SetMeta("og:type", "article");
  SetMeta("twitter:card", "summary");
}

@Display(Model.Metadata.ChildContent)

This will add the necessary meta tags to the current page, then render the shape it's wrapping as usual.

No Comments

Add a Comment