Steve Grunwell

Open-source contributor, speaker, and coffee snob

How did I not know about get_post_types_by_support()?

Every once in a while (well, more often then I’d care to admit, actually), WordPress core surprises me with a function that I had no idea existed. They often come in the form of utility functions, things written when developers decide “oh no, I have to write this piece of logic again?!”. Heck, there have even been talks on these hidden little bits of code that make the world a brighter place.

This week, that function is get_post_types_by_support().

Before I show you how it works, let me show you how we used to do it: you’re developing a feature that should be available across multiple post types, but you want post types to be able to opt-into it, the way they might opt-into post thumbnails, comments, etc.

In your post type definition (or by way of add_post_type_support()), you say “my post type will support the ‘my-cool-feature’ piece of functionality. Then, instead of messing around with filters full of post type slugs, your post type can easily express “yo, I want that.”

If your feature contains a custom meta box, you want to make sure that it’s available on the edit screens for all of the post types that support it, right? You probably end up with something like this:

Not too terrible, but it’s a bummer to have to get every post type and iterate through them to build that $screens array.

get_post_types_by_support(): a better way.

Fortunately, as of WordPress 4.5, we have the get_post_types_by_support() helper function, which gives us the names of any post types that support a given feature (or array of features).

If we refactor the same code from above to use get_post_types_by_support(), you’ll see its power:

Holy shit-snacks!

Thank you to everyone who contributed to Trac #34010, and especially to Travis Smith of WP Smith for making the recommendation and offering up the first patch!

How did I not know about…?

As I said before, WordPress core is riddled with some of these awesome little functions that fly under the radar of most of the development community. What are some of your favorite little-known functions that you can’t live without (or, at least, would prefer not to)?

Previous

Preparing for your Annual Review

Next

Cropping and Resizing Animated Gifs with Gifsicle

1 Comment

  1. That’s pretty snazzy. I wasn’t aware of that one either. Thanks for the brain dump!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Be excellent to each other.