As PHP has continued to move forward and WordPress (and its developer-economy) works to begin using more of the more modern features, one of the things we still see happening is the use of globals within WordPress.

To some degree, it’s inevitable: Significant parts of the application were built using globals when that was the facility that was a primary feature; other parts, though, have moved forward by providing classes or functions that prevent us from needing to do that.

Case in point: get_post_field is a solid alternative to using the $post global that provides much of the same information in a slightly more modern (and arguably safer) way of reading the data.

Functions in Place of Globals: get_post_field

For many, using something like the following is a common practice:

It’s not uncommon to see something like get_the_title(get_the_ID()); throughout code, which is a good thing, but there are still times where we see code written that access certain aspects of the current post.

Functions in Place of Globals: get_post_field

And I question how necessary that practice really is given the get_post_field function. From the Code Reference:

Retrieve data from a post field based on Post ID.

Examples of the post field will be, ‘post_type’, ‘post_status’, ‘post_content’, etc and based off of the post object property or key names.

A similar example to this function would be the get_user_by function where you pass a specific string to the function for which you want to retrieve information as well as an ID (or the full post object, but when the ID suffices, why not?).

The difference here is that you’ll retrieve the value of the requested field or an empty string (rather than an error or null or false) when the request fails. This means we’d need to write a conditional or a guard clause to handle such a case.

So a full use case of this function and the code may require a couple of functions:

That can all be tied together like this:

The point of sharing this kind of code is to help share some of the alternatives we have to global variables to also share APIs that exist but may be underutilized.