Rank Math插件硬编码作者图片URL报错,求PHP代码修正方案
解决Rank Math SEO硬编码作者图片URL的问题
我是WordPress新手,之前多次得到大家帮助,先致谢。我用Rank Math SEO高级版插件,它的Schema功能默认从Gravatar拉取作者图片,但我没使用Gravatar登录网站。因为我是网站唯一作者,想在Rank Math的PHP文件里硬编码作者图片URL。
原插件获取图片URL的PHP代码:
private function add_image( &$entity, $author_id, $jsonld ) { $entity['image'] = [ '@type' => 'ImageObject', '@id' => get_avatar_url( $author_id ), 'url' => get_avatar_url( $author_id ), 'caption' => get_the_author(), ]; $jsonld->add_prop( 'language', $entity['image'] ); }
我尝试改成下面的代码,想把指定URL设为@id并显示图片,结果触发严重错误,请问正确写法是什么?
private function add_image( &$entity, $author_id, $jsonld ) { $entity['image'] = [ '@type' => 'ImageObject', '@id' => echo 'https//mbastory.builders/wp-content/uploads/Leah-Derus-Circular-Light-Grey-500px.png#author', 'url' => $filepath= '\wp-content\uploads\Leah-Derus-Circular-Light-Grey-500px.png'; echo '<img src="'.$filepath.'">', 'caption' => get_the_author(), ]; $jsonld->add_prop( 'language', $entity['image'] ); }
你的错误原因:
- 数组赋值时不能使用
echo语句,数组元素需要直接赋值字符串,不能执行输出操作 - Schema的
url字段需要的是图片的完整HTTP/HTTPS URL,不是HTML的<img>标签,这个字段是给搜索引擎识别的资源地址,不是用于前端展示的代码 - 你写的URL格式错误,
https//要改成https://
正确的修改代码如下:
private function add_image( &$entity, $author_id, $jsonld ) { // 定义完整的作者图片URL $author_image_url = 'https://mbastory.builders/wp-content/uploads/Leah-Derus-Circular-Light-Grey-500px.png'; $entity['image'] = [ '@type' => 'ImageObject', '@id' => $author_image_url . '#author', // 保留锚点标记 'url' => $author_image_url, 'caption' => get_the_author(), ]; $jsonld->add_prop( 'language', $entity['image'] ); }
额外提醒:直接修改插件核心文件会导致插件更新后代码丢失,更稳妥的方式是使用Rank Math官方提供的过滤器(如rank_math/json_ld/author)来实现修改,不过如果你暂时不需要更新插件,上述硬编码的写法可以直接使用。
内容的提问来源于stack exchange,提问作者LCD
相关产品推荐
相关产品推荐

