How to make the XhtmlString <p> tag go away

Optimizely CMS is still using TinyMCE for the rich text (XhtmlString) fields. By default, everything you write in these fields is being wrapped in <p></p> tags. These extra tags can be a pain, as they do not always fit with the document structure. You do not need to create a bad experience for people in need of good document structure – taking control over your XhtmlStrings is easy!

Unwanted p's? Remove them!

The TinyMCE editor used by the XhtmlString fields is highly customizable. Removing unwanted tags can be done like this:

First, you must ensure that any non-block elements or text nodes are not wrapped in block elements. This is done by adding the setting "forced_root_block", and setting it to blank. If you are using TinyMCE before version 3.5, you must also have a couple more settings. One for "force_br_newlines", and one for "force_p_newlines".

To make this work in Optimizely, you will need to add these settings to your TinyMCE initializer.

            context.Services.Configure<TinyMceConfiguration>(config =>
                config.For<ArticlePage>(w => w.StrippedXhtmlField)
                    .Toolbar("cut copy paste epi-link unlink")
                    .AddSetting("forced_root_block", "")
                    .AddSetting("force_br_newlines", false)
                    .AddSetting("force_p_newlines", false)

If you need to do this for a CMS 12+ solution, you would probably want to move your InitializationModule to an extension method, as described here.

The result

The XhtmlString field.

Before adding new settings. My text is surrounded with the <p> tag.

After adding new settings. The magically inserted <p> tag is magically removed 🪄.