Show first n paragraphs as a teaser

Padlocks

I was working with a client recently who wanted to increase their newsletter signups by treating some of their long-form content as “premium content”, which was only available to their newsletter subscribers.

The idea was to show the first three paragraphs and then show the signup form if the user wasn’t already a newsletter subscriber. We did this by setting a cookie when the user signed up to the newsletter, which we then checked for when showing premium content, to either show the premium content, or show the newsletter subscription form instead.

Now back to how to limit the content we showed to the first “n” paragraphs (3 in our case). I used the the_content filter to change how the content appeared on the posts of my choosing. Here’s the snippet, and then I’ll explain it:

In line 6, you define how many paragraphs you want to display. In line 10, you set the conditions for which content is going to be restricted in this manner. In the example above, if the user isn’t logged in, the content will be restricted, but you could create any kind of conditional statement there, such as being on a certain custom post type, or a cookie being set in the browser in my own case.

Lines 11-20 is where the magic happens. The code “explodes” the content using the closing paragraph tag, so it creates an array of all of the paragraphs in your content. Line 13 makes sure that your content is at least as long as your paragraph limit, and lines 16-19 run a loop to show as many paragraphs as you defined. When it reaches your limit, as set in line 6, it goes on to display whatever message or form you want to display to those who can’t see all of the content, which is shown on line 22. In my case, I’m displaying a Gravity Form, to allow users to subscribe to the newsletter.

The remainder of the code just makes sure that those who are allowed to see the content, do in fact see it.

And there you have it. Those who meet the conditions you set will now see all of the content, and those who don’t will only see the first n paragraphs, and then the message or form of your choice.

Leave a Reply