Auto tweet new WordPress posts with categories as hashtags in Zapier

Automatically sending tweets for new posts on your WordPress site is a simple task with Zapier. Recently, though, I wanted to add hashtags for each category assigned to the WordPress post and include that in the tweet as well. Can Zapier accommodate this?

Yes, it can, although it turned out to be a bit more difficult than I anticipated.

The problem

On the surface, it seemed like a simple problem. Each new WordPress post sent through Zapier brings along a comma-separated list of all categories assigned to it. Turning that into hashtags requires only four steps:

  • Remove any spaces from inside each category name
  • Transform each category name to lower case (not strictly necessary, but we might as well as hashtags aren’t case sensitive)
  • Remove the commas from the list
  • Append the number sign to each category to make it a hashtag

The solution

My first thought was to use Zapier’s built-in formatter actions to accomplish all of the above. The formatter allows us to split a comma separated list into individual line items, replace specific characters within each line item, lower case each line item, and even append characters to each line item.

However, try as I might, I couldn’t get consistent results with this approach. (Appending the # character to each line item is where I got stuck. I still think it’s possible with the formatter actions, but after 30 minutes or so I decided to try a different approach).

Fortunately, Zapier lets us drop blocks of javascript code as custom actions into our zaps. So I wrote this snippet to take care of all four steps in one action:

var busted = inputData.categories.split(',');
var hashray = busted.map(i => i.toLowerCase());
var hashray = hashray.map(i => '#' + i);
var hashray = hashray.map(i => i.replace(/\s/g, '')); 
var hashtags = hashray.join(" ");
output = { hashtags };

Here’s how it works:

  1. Take the comma separated list and split it into an array (what Zapier calls line items).
  2. Lower case each item in the array
  3. Add the hashtag symbol to each item
  4. Remove any spaces within each item
  5. Join each item in the array back into a single line of text, with each item separated by a space
  6. Return the finished output for use in the next action

To use the above code, create a zap triggered by a new post on your WordPress site.

Then add a code action and select Javascript as the language.

Next copy and paste the code snippet above into the code field, and fill out the input data fields as listed in the screenshot below.

Finally, add a Twitter action to push the title, link, and hashtags for your new post to Twitter.

And that’s it. Each new post on your WordPress site will now automatically send a tweet to the post, complete with hashtags for each of your post categories.

Are you struggling with automating parts of your business with Zapier? Get in touch to see how I can help.

Should you enable automatic updates in WordPress?

One of the headline features in the recent release of WordPress 5.5 was the ability to enable automatic plugin and theme updates. This follows the inclusion of automatic core updates in WP 3.7.

On paper, the arguments for automatic updates are compelling. They’re the fastest and most reliable way to patch security exploits, for instance, and most users are woefully lax in remembering to update their sites on their own. (Clients frequently hire me to debug and update installations that haven’t been touched in a more than a year, so I’m more sympathetic than some to the problems that automatic updates are intended to solve.)

Unfortunately, this is yet another area where good intentions go terribly awry. At this point in time, automatic updates in WordPress remain a dangerous, unstable, and unworkable idea by every practical measure.

For proof of this we need look no further than the release of WordPress 5.5 itself, which contained breaking changes in core javascript libraries that caused issues on many sites. This was followed a few days later by an update to Woocommerce that introduced conflicts and fatal errors of its own (particularly on those sites running my favorite caching plugin WP Rocket).

So this week alone, you could have found your site broken by an automatic core update to WordPress 5.5, and then, had you turned on the new automatic plugin updates, found your site broken again in less than 48 hours by a Woocommerce update.

The most significant thing about these examples is that they weren’t caused by little known plugins or themes from unproven developers — they were introduced by the WP core dev team and the WooCommerce dev team, some of the most experienced and proven talent in the WP ecosystem.

I don’t intend at all to beat up on the core devs or the Woocommerce devs with these remarks. Bugs happen — and I’ve certainly introduced more than my share of them into my own code. The problem with automatic updates isn’t the quality of the code coming from the best devs in our community but the nature of WordPress itself. Automatic updates work great on a closed ecosystem like Apple’s app store — an ecosystem where the hardware options are limited, quantified, and controlled, and where all software is screened to at least some degree before it’s allowed on the platform.

But WordPress is an entirely different animal. The infinite variety (and varying quality) of third-party plugins, theme frameworks, and laughably underpowered shared hosting plans makes automatic updates a recipe for disaster. It’s impossible to test even a fraction of every possible plugin, theme, and hosting combination. As long as that’s true, automatic updates are a fool’s errand.

Furthermore, to try and change these fundamental issues to make automatic updates more reliable would necessarily kill the openness and flexibility that has made WordPress such a global success.

So should you enable automatic updates in WordPress? Absolutely not.

If not automatic updates, then what? A workable approach to updates

With all that said, here is my approach to updates on the sites I manage (and the recommendations I give to my clients).

  • Set a workable update schedule, put it on your calendar, and stick to it. You don’t need to check your site for updates every day. Updating once per week will put you ahead of 95 percent of the WP sites out there, and updating even once every couple of weeks is still enough to avoid critical problems in my experience.
  • Don’t apply updates to your site until they’ve been in the wild for a week or so. This bit of lag time will allow developers to address any unexpected bugs or conflicts without your site suffering the fate of a neglected lab rat. The only exceptions to this policy are critical security updates. If the release notes for a plugin or core update mention a security fix, it’s best to cross your fingers and apply those as soon as you see them.
  • If you’re using paid or premium plugins, be sure you have activated your license codes and are receiving update notices. A common problem in my client work are premium plugins and themes that weren’t activated to receive updates. So the site owner conscientiously updates the rest of their installation on schedule but is eventually stopped cold by a fatal error because they were never notified that updates were available for a particular plugin or theme.
  • Make sure you have a backup system in place. Even when you’re careful and apply updates on a reasonable schedule, something will eventually break. When this happens, the ability to quickly roll back to a working backup will prevent you from adding bourbon to your breakfast cereal.
  • Whenever possible, test updates on a staging site before applying them on your live site. Whether you can easily do this depends almost entirely on your web host. Specialty hosts like WPEngine offer automatic staging sites and one click copying of your live site to a staging area, where you can safely test updates. But the junkyard Cpanel shared hosting abominations that power most WP sites offer nothing of the sort. (I will save my hosting rant for another time).

Finally, if you’re going to allow any automatic updates, I recommend enabling only security and minor updates for the core. You can enable core security updates alone by adding the following line to your wp-config.php file:

define( 'WP_AUTO_UPDATE_CORE', minor );

Are you struggling with updates or other problems on your WordPress site? Book an appointment in my WP Clinic, and we’ll work through it together.

Introducing Well Adjusted, a new podcast about horror movies and culture

I can’t remember the first horror movie that I saw. I started young — too young for today’s ninny standards — by dragging my babysitter to the local video rental store during my parents’ weekly outing and insisting I was allowed to watch whatever. Whenever she balked at a particularly gory or salacious cover, my little brother and I would shrug casually and say, don’t worry, we’ve seen a lot worse.

It was the 80s in Arkansas. Kids could still buy cigarettes without too much trouble, so a handful of R rated VHS tapes weren’t a hard sell.

Fast forward to adulthood, and I’ve continued watching those old films, as well as many contemporary horror releases, and I still get the same giddy thrill when the camera switches to the monster’s POV or the formerly meek heroine drops the whimpering veneer of socialization and goes at the killer with a fireplace poker.

When you love something, you can’t help but want to share it. For the longest time now I’ve wanted to find a forum where I could talk about these films and the horror genre in general. Well, yesterday my friend Levi Horne and I finally made it a reality.

Well Adjusted is a weekly podcast about horror movies and books and their relationship to our larger culture. In the first episode, we discuss Larry Cohen’s 1974 B movie masterpiece It’s Alive. It’s the perfect movie to watch for expecting parents, or anyone contemplating starting a family.

Give it a listen, and subscribe in your favorite podcast platform if you are so inclined. This plague season has been a dry well creatively — for obvious reasons — and making this little project a reality felt like the sun came out for the first time all year.

Dashboard problems after updating to WordPress 5.5? Install this plugin.

WordPress 5.5 was released last night, and it began the long process of updating the bundled jQuery javascript library to a more current version. Unfortunately, it also broke a number of plugins and themes, causing javascript errors and strange behavior throughout the dashboard and front end.

The first problem I noticed on my site were broken hover states in the WordPress admin dashboard. Typically, when you hover the Posts or Pages or any side menu in the dashboard, a submenu appears to display the related options.

The WordPress 5.5 update broke the hover state in my dashboard menus, preventing the submenu items from displaying on hover.

The cause turned out to be the removal of a script called jQuery migrate from the WordPress core — a necessary first step in the jQuery update process. The solution is to put the script back. Fortunately, the WP core team anticipated this would be an issue on some sites and kindly provided a free plugin to address the issue.

If you notice strange behavior after updating — and especially if you see errors in the javascript console — try installing the Enable jQuery Migrate Helper plugin. It fixed my issues straight away.

Are you struggling with updates or other problems on your WordPress site? Book an appointment in my WP Clinic, and we’ll work through it together.

How photography helped me recover from depression

Early last year I bought a new camera. I’d been a casual shutterbug at various times before, but always wound up quitting within a few weeks or months. This time, though, was different. This time, the perfectionism and anxiousness and preordained sense of defeat that clung to every previous snap of the shutter were gone. This time, I wasn’t shooting to prove to some unseen force that I had intrinsic worth. This time, I was shooting just to shoot.

Read more “How photography helped me recover from depression”

Three tips for testing and debugging javascript in Zapier code actions

Zapier is bar none the handiest utility in existence for automating online workflows and connecting different online services. This was true even before the introduction of custom code actions, which allow you to drop in blocks of javascript and python code to manipulate data in your zaps, and it’s doubly true now.

Debugging and testing custom code in Zapier, however, takes a little getting used to, especially if you’re accustomed to more traditional programming tools. Here are three immediate things to keep in mind as you get started:

  1. Javascript code actions must return either an object or an array of objects. This is all well and good, but if you expect your code to return an array when testing your action within Zapier, you may find yourself confused when the test outputs only the first item of your array. You may then find yourself checking your code, over and over again, then your input, over and over again, then your favorite swear words, then your sanity. But the truth is your code is working fine, and Zapier is working fine: testing a code action will output only the first object in an array, no matter how many objects are actually in the array. This is only true of testing your zap; when the zap actually runs, the full array will be processed.
  2. The above behavior seems counterintuitive (I mean, why wouldn’t someone expect to see the full output of their array in a test?), until you consider this: any subsequent action after your code will process each item in the returned array individually. For instance, if your code returns an array with four items, and the following action is Zapier’s stock text formatter to transform all upper case letters to lower case letters, then the text formatter will loop through all four, acting on each in order. So, when the test in Zapier shows you only the first item in your multi-item array, it’s showing you the data that will be immediately passed to the next action, which is the most relevant thing when chaining actions together in your zap. It takes a minute to wrap your head around, but when you get it everything falls into place.
  3. Logging to the console is your friend. Drop in a console.log(your-array-variable-here) within your code action to confirm the full contents of your array during testing. The output of console.log will show in the test output under the logs key.
Javascript code that returns an array of objects will display only the first item of the array in the Zapier test output. But the full array will be processed when the zap is run. In this example, the zap returned the first url in an array of urls, using this javascript code for pulling all URLs from any text.
Use console.log() in your Zapier javascript code to verify the full contents of an array when testing your code action.

How to use Zapier to extract all URLs from a text source

Here’s a nifty trick for pulling all of the URLs out of text with a Zapier javascript code action.

Using this, you can extract URLs from any Zapier text input. For instance, you could use the Zapier email trigger to pull all of the URLs from an email message, or you could use the push button trigger to pull the URLs from a webpage.

The code is based on Zapier’s example documentation for extracting email addresses from text, combined with this handy regex for extracting URLs.

Here’s the code, which you can paste into a Zapier javascript code action:

var urls = inputData.rawText.match(/\b((?:[a-z][\w\-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\((?:[^\s()<>]|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi) || [];
return urls.map(function(url) {
  return {url: url};
});

The output will be an array of javascript objects, which you can then process with other Zapier actions. If you’re new to working with code actions in Zapier, check out these tips for testing Zapier code actions and working with arrays.