Ok, maybe I’m the last on to arrive at the party on this, but I somehow never realized that you can get any post_meta field by using its key as a property of a WP_Post object. Pretty useful. It means that if you have a WP_Post object, and the post it represents has a meta_key called “josh,” you don’t need to use get_post_meta(), you can use $post->josh. Here are some examples: How does it work? It works thanks to the way the __get() magic method is used in the WP_Post class. If a class has this magic method, it will run anytime a property that doesn’t actually exist is called. In WP_Post it is used for a few fields that are not in the post table, and therefore are not retrieved by the main query for the post. As always, taking a look at the source, and then trying it out, is the best way to learn. Here is the __get() from WP_Post, copied from the source for your convenience: Why am I thinking about this? In Caldera Forms we have the ability to auto-populate select fields from a specific post type, or taxonomy. I’m working on adding an autocomplete/ select2 field type that will be able to use this auto-population option. As a result, I’m looking at how to make them more useful and flexible.
Share This