WordPress PHP插件添加SportsEvent Schema Json-ld报错求助
解决SportsEvent Schema插件的PHP语法错误问题
嘿,这个问题很典型——你触发的语法错误完全是因为PHP数组的语法规则没遵守。咱们一步步来解决:
错误根源
PHP数组里的键值对之间必须用逗号(,)分隔,但你代码里所有数组元素结尾都用了分号(;),这就导致解析器找不到预期的括号,直接报错。另外还有几个小细节需要调整,不然即使语法过了,Schema也不会正常工作。
修正后的完整代码
<?php /** * Plugin Name: Schema.org for Football * Description: Add SportsEvent Schema.org in JSONld to site * Plugin URI: * Author: Danstan * Author URI: * Version: 1.0.0 * License: GPL2 or later * License URI: https://www.gnu.org/licenses/gpl-2.0.html */ function addschema() { // 补全缺失的函数起始花括号 global $post; if (is_singular('matches')) { //仅针对matches自定义文章类型 $schema_sportsevent = array( '@context' => "http://schema.org", '@type' => "SportsEvent", 'name' => get_the_title($post->ID), 'description' => wp_strip_all_tags(get_the_content($post->ID)), // 移除HTML标签,适配Schema规范 'url' => get_permalink($post->ID), 'startDate' => get_post_meta( get_the_ID(), 'start_date', true ), // 加true获取单个字符串值 'endDate'=> get_post_meta( get_the_ID(), 'end_date', true ), 'image' => get_the_post_thumbnail_url($post->ID), 'competitor' => array( // 改为数组嵌套,避免重复键覆盖问题 array( '@type' => "SportsTeam", 'name' => "Team A", 'image' => get_post_meta( get_the_ID(), 'logo_left', true ) ), array( '@type' => "SportsTeam", 'name' => "Team B", 'image' => get_post_meta( get_the_ID(), 'logo_right', true ) ) ), 'location' => array( '@type' => "Place", 'name' => get_post_meta( get_the_ID(), 'venue_name', true ), 'address' => array( '@type' => "PostalAddress", 'postalCode' => get_post_meta( get_the_ID(), 'zip_postal_code', true ), 'streetAddress' => get_post_meta( get_the_ID(), 'street_address', true ), 'addressLocality' => get_post_meta( get_the_ID(), 'locality_city', true ), 'addressRegion' => get_post_meta( get_the_ID(), 'address_region', true ), 'addressCountry' => get_post_meta( get_the_ID(), 'country', true ) ) ) ); echo '<script type="application/ld+json">' . json_encode($schema_sportsevent) . '</script>'; // 编码为JSON-LD输出 } } // 替换错误的endif;,用花括号闭合if代码块 add_action('wp_head', 'addschema'); // 将Schema添加到页面头部 ?>
关键修改点说明
- 数组分隔符修正:所有数组元素结尾的
;全部替换为,,这是PHP数组的强制语法要求 - 修复
get_post_meta返回值:添加第三个参数true,确保返回单个字符串而不是数组,避免JSON编码后出现无效结构 - 修复重复的
competitor键:原代码中两个同名键会导致后一个覆盖前一个,改成嵌套数组才符合SportsEvent Schema的多参赛队伍规范 - 语法结构修正:补全函数起始的花括号,替换错误的
endif;(因为你用花括号包裹if代码块,需用}闭合) - 优化
description字段:用wp_strip_all_tags移除内容中的HTML标签,避免Schema里出现无效代码
这样修改后,插件应该能正常激活,并且输出符合规范的SportsEvent Schema了。
内容的提问来源于stack exchange,提问作者user9258693
相关产品推荐
相关产品推荐

