Thursday, May 18, 2023

Getting YouTube, WordPress and Mailchimp to All Play Nice Together

Our shul is making its way through the Counting of the Omer using our Omer Learning project. I've set this virtual program up so that nightly a new WordPress post is published that mentions the count of the Omer and includes a bit of community contributed wisdom. A few minutes after the post is published, Mailchimp queries our website's XML feed and sends out an e-mail with the recently published content. This has been working smoothly and allows me to schedule content weeks in advance, yet emails trickle out nightly.

Two nights ago we published the 41st day of the Omer by sending out this email:

A keen eyed congregant noticed a problem (thanks Howard!): the YouTube link mentioned in the submission is missing. Oy vey.

At first, I assumed this was operator error: when I set up this submission I probably neglected to include the link. But, looking at the 41st day of the Omer on our website, I see the video just fine:

Once I saw the video expanded in the page, I realized what was going on. WordPress noticed that I had included a YouTube link in the post content:

It then expanded this simple URL into an <iframe> embed. This is generally a good thing. But it included that same <iframe> embed in the XML feed that Mailchimp crawls. Mailchimp, operating in the world of HTML e-mail, was quick to strip out the <iframe>, and in doing so, chuck the YouTube video from the message.

I now understood what was going on, but how could I stop it?

One possibility was to make the YouTube URL less attractive to WordPress. If I changed it from https://youtube/... to just youtube/..., WordPress wouldn't expand it into an <iframe>. But, users on the website would no longer have quick access to the video. Besides, the <iframe> embed approach looks quite nice on the website.

I realized what I wanted to do was tweak the post content as it was generated for the XML feed. This being WordPress, I hoped there was a hook I could tap into to do this. Sure enough, there is: the_content_feed. Once I figured out the strategy and hook to use, implementing a filter that turned <iframe> embeds into simple links was easy enough to code. I put the following in functions.php in our WordPress theme:

add_filter('the_content_feed', function($content) {
  $content = preg_replace('|<iframe.**?)[?].*></iframe>|', 
                          '<a href="$1">$1</a>', 
  return $content;

Last night's Omer Learning once again included YouTube links. On the website, they expanded to playable videos:

In the feed, these <iframe>'s were turned into simple links:

In the e-mail that was sent out, the YouTube links came through nice and clear:

Problem solved! This is such a classic WordPress gotcha: it's mystery behavior that can be fixed with just a few lines of code. You have to both love and hate WordPress for this.

No comments:

Post a Comment