给Google"喂"数据(下)

上一期通过修改源码的方式解决了Missing field "aggregateRating"和Missing field "review"两项,后来在谷歌后台检测网站时又发现Missing field "hasMerchantReturnPolicy" (in "offers")和Missing field "shippingDetails" (in "offers"),总是修改源码不是好的办法,今天把woocommerce网站翻了个遍,终于找到了可以修改Structured Data的hooks了。

1、修改系统现有的Structured Data

1
2
3
4
5
6
add_filter( 'woocommerce_structured_data_product', function( $schema, $product ) {
$schema['name'] = 'Your new products name here';
$schema['description'] = 'Your new products description here';
$schema['image'] = 'Link to your new product image here';
return $schema;
}, $priority = 20, $accepted_args = 2 );

没错,就是这个filter:woocommerce_structured_data_product!

2、添加系统没有的Structured Data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
add_filter( 'woocommerce_structured_data_product', function( $schema, $product ) {
$schema['brand'] = 'CartBounty';
$schema['review'] = array(
'@type' => 'Review',
'author' => 'Name of the author here',
'datePublished' => '2019-10-04',
'name' => 'Review title here',
'description' => 'Description of our review here',
'reviewRating' => array(
'@type' => 'Rating',
'bestRating' => 5,
'worstRating' => 1,
'ratingValue' => 5
),
);
return $schema;
}, $priority = 20, $accepted_args = 2 );

增加数据的办法和修改是一样的,用的同一个filter,但是有没有注意到(in "offers")这几个字母?说明我们要怎加的参数是在offers里面,但是我们系统中已经有了offers这个参数了,那么我们要在offers里面添加新的参数应该如何操作呢?见下面的代码:

1
2
3
4
5
6
7
8
9
10
add_filter( 'woocommerce_structured_data_product_offer', function( $schema, $product ) {
$schema['hasMerchantReturnPolicy'] = array(
'applicableCountry' => 'US',
'returnPolicyCategory' => 'https://schema.org/MerchantReturnFiniteReturnWindow',
'merchantReturnDays' => 60,
'returnMethod' => 'https://schema.org/ReturnByMail',
'returnFees' => 'https://schema.org/FreeReturn'
);
return $schema;
}, $priority = 20, $accepted_args = 2 );

对!用了另外一个filter:woocommerce_structured_data_product_offer,至此就可以把 hasMerchantReturnPolicy 和 shippingDetails 给解决掉了。

3、另外的收获

最后送点小知识,要想完全移除Structured Data,用下面的代码可以解决掉:

1
2
3
4
function remove_wc_structured_data() {
remove_action( 'wp_footer', array( WC()->structured_data, 'output_structured_data' ), 10 );
}
add_action( 'init', 'remove_wc_structured_data' );
Author

MelonCloud

Posted on

2024-11-06

Updated on

2024-11-06

Licensed under

Comments