So I have this code for outputting schema, which works correctly, but it gives me a bool error. “Trying to access array offset on value of type bool”
I am grabbing the address variables from another loop on the page $map_location and adding the sub variables into $contact_numbers. As they both share the same content.
Is there a relatively easy way around this?
/**
* 'wp_head' callback
* Insert structured data into head
*/
public function add_address_schema() {
// Return if not hospital post.
if ( get_post_type() !== 'location' ) {
return;
}
global $luna;
$id_post = get_the_id();
$map_location = get_field( 'map_location', $id_post );
$contact_numbers = get_field( 'contact_numbers', $id_post );
$thumbnail_id = get_post_thumbnail_id( $id_post );
$location_type = $luna->utils->get_the_primary_term( 'location-type', $id_post );
$address_schema = [
'@context' => 'https://schema.org',
'@type' => $location_type ? $location_type->name : __( 'Hospital', 'luna' ),
'name' => get_the_title( $id_post ),
'url' => get_the_permalink( $id_post ),
];
if ( $thumbnail_id ) {
$address_schema['image'] = get_the_post_thumbnail_url( $id_post, 'large' );
}
if ( $map_location ) {
$address_schema['address'] = [
'@type' => 'PostalAddress',
'streetAddress' => $map_location['address'],
'addressLocality' => $map_location['city'],
'addressRegion' => $map_location['state'],
'postalCode' => $map_location['post_code'],
'addressCountry' => $map_location['country_short'],
];
$address_schema['geo'] = [
'@type' => 'GeoCoordinates',
'latitude' => $map_location['lat'],
'longitude' => $map_location['lng'],
];
}
if ( $contact_numbers && is_array( $contact_numbers ) ) {
$address_schema['department'] = [];
foreach ( $contact_numbers as $contact ) {
$address_schema['department'][] = [
'@type' => $location_type ? $location_type->name : __( 'Hospital', 'luna' ),
'name' => $contact['label'],
'telephone' => $contact['number'],
'@type' => 'PostalAddress',
'streetAddress' => $map_location['address'],
'addressLocality' => $map_location['city'],
'addressRegion' => $map_location['state'],
'postalCode' => $map_location['post_code'],
'addressCountry' => $map_location['country_short'],
];
}
}
echo '<!-- Auto generated address structured data --><script type="application/ld+json">' . wp_json_encode( $address_schema, JSON_PRETTY_PRINT ) . '</script>';
}
}