如何解决跨循环调用变量时的布尔类型错误?
解决“Trying to access array offset on value of type bool”错误的方案
错误原因
报错的核心问题是:在遍历$contact_numbers的循环里,你直接调用$map_location['address']这类数组键,但$map_location可能是布尔值false(当该自定义字段未填写内容时),此时尝试访问布尔值的数组偏移量就会触发这个错误。另外你在部门的Schema结构里重复写了@type字段,这会导致JSON结构异常。
修复方案
- 提前判断
$map_location是否为有效数组,再在循环中复用地址信息; - 提取地址信息为独立变量,减少重复代码;
- 修复重复的
@type字段,保证Schema结构合规。
修改后的完整代码
/** * '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_details = []; if ( $map_location && is_array( $map_location ) ) { $address_details = [ '@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 = [ '@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 ( !empty( $address_details ) ) { $address_schema['address'] = $address_details; $address_schema['geo'] = [ '@type' => 'GeoCoordinates', 'latitude' => $map_location['lat'], 'longitude' => $map_location['lng'], ]; } if ( $contact_numbers && is_array( $contact_numbers ) && !empty( $address_details ) ) { $address_schema['department'] = []; $dept_type = $location_type ? $location_type->name : __( 'Hospital', 'luna' ); foreach ( $contact_numbers as $contact ) { $address_schema['department'][] = [ '@type' => $dept_type, 'name' => $contact['label'], 'telephone' => $contact['number'], 'address' => $address_details // 复用提前准备好的地址信息 ]; } } echo '<!-- Auto generated address structured data --><script type="application/ld+json">' . wp_json_encode( $address_schema, JSON_PRETTY_PRINT ) . '</script>'; }
关键修改点
- 新增
$address_details变量,统一处理地址信息,避免重复编写相同代码; - 在处理
contact_numbers时,增加!empty( $address_details )的判断,确保只有当地址信息存在时才添加到部门结构中; - 修复了部门结构里重复的
@type问题,把地址信息作为address子节点嵌套,符合Schema规范; - 所有访问
$map_location的地方都增加了数组类型判断,避免布尔值导致的错误。
内容的提问来源于stack exchange,提问作者Ruth
相关产品推荐
相关产品推荐

