Embedding Tweets and other Twitter widgets in WordPress is super useful and popular. The automatic oEmbed functionality in WordPress makes it as easy as grabbing a Tweet URL and dropping it in to your post. oEmbed returns the correct HTML to make the Tweet render nicely on your site.

Many sites, GeekWire included, have Twitter functionality on nearly every page. Most commonly this is tied to your Tweet button, though you may also host Twitter timeline widgets in your sidebar or similar.

When you host Twitter functionality this frequently, it makes sense to host Twitter’s widgets.js script directly in your site template. That way it is always available and you can skip re-embedding the script over and over again if you host multiple Twitter widgets on a page.

The default Twitter oEmbed functionality is great, but it assumes that you are not serving widgets.js already in your site template. The default oEmbed call goes something like this:

  1. Get the URL of what you are trying to embed (Tweet, Youtube video, etc)
  2. Identity the provider from the URL (Twitter, Youtube, etc)
  3. Grab the oEmbed endpoint for that provider
  4. Fetch the HTML for the embed object from the oEmbed provider’s defined endpoint
  5. Cache the HTML
  6. Render HTML on your page

In the case of a Twitter Tweet embed, Twitter will return the HTML needed to render the tweet, plus it will append a call to the widgets.js script at the end of the Tweet’s HTML, since you do need the script to have the tweets render properly. If you send a URL to Twitter’s oEmbed endpoint with a query arg of omit_script=true, it will return only the HTML.

In our case, we’re already loading widgets.js in the footer of every page. We needed a way to remove the duplicate calls to widgets.js and a relatively new and obscure oembed_fetch_url filter in WordPress does the trick.

Latest Developer Blog Articles

Job Listings on GeekWork

Find more jobs on GeekWork. Employers, post a job here.