thoughtis / cata-co-authors-plus

Common functions, configuration and compatibility fixes for Co-Authors Plus when used in Cata child themes. Not a fork or replacement for CAP.
GNU General Public License v3.0
0 stars 0 forks source link

Get author data with consistent return types #4

Closed douglas-johnson closed 3 years ago

douglas-johnson commented 3 years ago

Because a post can have multiple guest authors, some of the CAP functions return associative arrays.

So if for example you wanted the name of a single author, you can wind up with something like this:

get_the_coauthor_meta( 'display_name', $author->ID )[$author->ID]

But you should probably prove that the author is in the returned array first. It's not very safe.

On Shop Catalog we handled that problem as shown below, and we did roughly the same thing on Creepy Catalog.

You pass the author in question to the shopcatalog_get_coauthor_data function, provide the property you want and a default response.

Note: This was built specifically for Guest Authors, stdClass $author would cause an error if a WP_User was provided instead.

/**
 * Safe Get Object Property
 * 
 * @param  string $property - the key / property we want.
 * @param  mixed  $object - the thing we hope is an object with that property.
 * @return mixed  $object->$property or $default.
 */
function sc_safe_get_object_property( string $property, $object, $default = null ) {
    if ( ! is_object( $object ) ) {
        return $default;
    }
    if ( property_exists( $object, $property ) ) {
        return $object->{$property};
    }
    return $default;
}
/**
 * Get CoAuthor Data
 * 
 * @return mixed $author->$property | $default.
 */
function shopcatalog_get_coauthor_data( string $property, stdClass $author, $default = null ) {
    return sc_safe_get_object_property( $property, $author, $default );
}
douglas-johnson commented 3 years ago

I didn't solve this exactly the same way as Shop Catalog. As I mentioned in the initial issue that version supported properties added through ACF rather than CAP and it only worked for Guest Authors.

In #10 I added a wrapper around a built-in CAP function to make something that works for CoAuthors whether they're users or Guest Authors, and only for data applied through CAP.

We may need something else later if we add data another way, but we'll cross that bridge yada yada.