沙唐桔

WordPress AMP 页面结构化数据提示 logo 和 image 错误

WordPress 启用 AMP,使用 Google 结构化数据测试工具检测页面可能会提示 logo 和 image 错误。image 错误很容易解决:文章设置一张特色图片就行。logo 错误目前应该要修改 amp 插件代码才行。

Google 文档:文章机构化数据规范

测试工具:结构化数据测试工具

老杨没有设置特色图片,每一篇文章设置是不可能的,可以用插件(Default featured image)设置,不过老杨选择了直接修改插件文件。

相关代码在:\amp\includes\amp-helper-functions.php 文件,amp_get_schemaorg_metadata() 函数。修改后代码:

function amp_get_schemaorg_metadata() {
$metadata = [
'@context' => 'http://schema.org',
'publisher' => [
'@type' => 'Organization',
'name' => get_bloginfo( 'name' ),
],
];

$metadata['publisher']['logo']['@type'] = "ImageObject";
$metadata['publisher']['logo']['url'] = get_bloginfo('template_directory').'/img/apple-touch-icon.png';


$post = get_queried_object();
if ( $post instanceof WP_Post ) {
$metadata = array_merge(
$metadata,
[
'@type' => is_page() ? 'WebPage' : 'BlogPosting',
'mainEntityOfPage' => get_permalink(),
'headline' => get_the_title(),
'datePublished' => mysql2date( 'c', $post->post_date_gmt, false ),
'dateModified' => mysql2date( 'c', $post->post_modified_gmt, false ),
]
);

$post_author = get_userdata( $post->post_author );
if ( $post_author ) {
$metadata['author'] = [
'@type' => 'Person',
'name' => html_entity_decode( $post_author->display_name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
];
}

if ( get_post_meta(get_the_ID(), 'thumbnails-120', true) ) {
$post_image_meta = [
'@type' => 'ImageObject',
'url' => get_post_meta(get_the_ID(), 'thumbnails-120', true),
'width' => "120px",
'height' => "120px",
];
} else {
$post_image_meta = [
'@type' => 'ImageObject',
'url' => get_bloginfo('template_directory').'/img/random/thums-'.sprintf( "%02d", rand( 1, 12 ) ).'.png',
'width' => "120px",
'height' => "120px",
];
}
$metadata['image'] = $post_image_meta['url'];


/**
* Filters Schema.org metadata for a post.
*
* The 'post_template' in the filter name here is due to this filter originally being introduced in `AMP_Post_Template`.
* In general the `amp_schemaorg_metadata` filter should be used instead.
*
* @since 0.3
*
* @param array $metadata Metadata.
* @param WP_Post $post Post.
*/
$metadata = apply_filters( 'amp_post_template_metadata', $metadata, $post );
}

/**
* Filters Schema.org metadata for a query.
*
* Check the the main query for the context for which metadata should be added.
*
* @since 0.7
*
* @param array $metadata Metadata.
*/
$metadata = apply_filters( 'amp_schemaorg_metadata', $metadata );

return $metadata;
}

请根据实际修改红色字体部分内容。

也可以到 Google Search Console - AMP 检查是否有错误。

--- 完 ---