When upgrading our website to PHP 8.0, we are faced with the following error:
Warning: Trying to access array offset on value of type bool
This relates to the following line of code:
$meta_value = $meta_values[ $meta_tuple['object_id'] ];
Code for the whole function is:
function wpsc_get_meta( $meta_key, $object_type, $object_id = 0 ) {
global $wpdb;
$cache_object_id = $object_id = (int) $object_id;
$meta_key = wpsc_sanitize_meta_key( $meta_key );
$meta_tuple = compact( 'object_type', 'object_id', 'meta_key' );
$meta_tuple = apply_filters( 'wpsc_get_meta', $meta_tuple );
// Get cached meta
$meta_value = wp_cache_get( $cache_object_id, $meta_tuple['object_type'] );
// If not cached, get and cache all object meta
if ( $meta_value === false ) {
$meta_values = wpsc_update_meta_cache( $meta_tuple['object_type'], $meta_tuple['object_id'] );
$meta_value = $meta_values[ $meta_tuple['object_id'] ];
}
if ( isset( $meta_value[ $meta_tuple['meta_key'] ] ) ) {
return maybe_unserialize( $meta_value[ $meta_tuple['meta_key'] ] );
}
return '';
}
Any suggestions how we could fix the above code for PHP 8.0 compatibility?
Rolled back to PHP 7.4, and the warning disappears.
You can change this
if ( isset( $meta_value[ $meta_tuple['meta_key'] ] ) ) {
return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}
to (see Null coalescing operator)
if ($meta_value[ $meta_tuple['meta_key']] ?? null)
return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}
or (old school)
if (
is_array($meta_value)
&& isset( $meta_value[ $meta_tuple['meta_key'] ] )
) {
return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}