Is there a way to extend WP_query so Custom Post Types can have properties?

Having trouble finding info on this. When working with lots of metadata/custom fields, I would really prefer to simplify getting the meta data inside of templates instead of using get_post_meta and instead keep the setting up of that data in the back-end where it belongs to keep my templates clean and easier to work with.

Is there a way to do this?

p?php echo $something-meta_field_name ?/p

This would be similar to how you can do things like $post-ID or $post-post_parent that are in WordPress core, except it would be for custom post types and custom fields. If this is not possible, I guess the next question would be, why?


Edit: Since I've seen this mentioned several times in responses, when writing PHP like this you have to escape the output, which I do. I left out the escaping for brevity, but for anyone new to it, here's how I would typically write this (and thanks to @fuxia for the solution to my original question).

Escaping (with the solution) for WordPress:

p id=text-?php echo esc_attr($post-post_name) ??php echo esc_html($post-meta_key_name) ?/p

And if you're outputting to a class:

p class=text-?php echo sanitize_html_class($post-post_title) ?Clean Class/p

I typically wouldn't use post_title but using it as an example as sanitize_html_class will remove white space and only keep alphanumeric characters, underscores and dashes.

If outputting things like JSON-LD, you can combine escaping:

@id: ?php echo esc_js(esc_url($link)) ?#?php echo esc_js($post-post_name) ?,
name: ?php echo esc_js($post-post_title) ?

Topic post-meta variables wp-query Wordpress

Category Web


Getting meta data from a WP_Post object is already possible. Just write:

echo $post->your_meta_key;

This will call get_post_meta( $this->ID, $your_meta_key, true ) behind the scenes.

See the documentation and the source code for WP_Post.

This works also with instances of WP_User, but not with WP_Comment as far as I know.

Don't forget to escape the output!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.