我使用它向每个产品的架构添加自定义字段
add_filter( 'woocommerce_structured_data_product', function( $markup, $product ) {
if( is_product() ) {
$markup['brand'] = get_post_meta(get_the_ID(), 'brand', TRUE);
}
我还需要将产品的图像网址和描述添加到架构中,如何实现此目的?
最佳答案
woocommerce_structured_data_product
Hook 已在产品页面上运行,因此您不需要 is_product()
检查。
正如 documentation 中所报告的,它在 woocommerce_single_product_summary
Hook 内执行。
您可以像这样覆盖结构化数据:
// overwrites structured data
add_filter( 'woocommerce_structured_data_product', 'set_structured_data', 99, 2 );
function set_structured_data( $markup, $product ) {
$markup['brand'] = get_post_meta( $product->get_id(), 'brand', true );
$markup['image'] = wp_get_attachment_url( $product->get_image_id() );
$markup['description'] = wp_strip_all_tags( $product->get_short_description() ? $product->get_short_description() : $product->get_description() );
return $markup;
}
代码已经过测试并且可以工作。将其添加到事件主题的functions.php中。
在产品页面上,找到 <script type="application/ld+json">
元素,它应该如下所示:
然后检查 brand
、 image
和 description
字段是否已赋值。
您可以在此处找到要添加到产品结构化数据的字段的完整列表:
如果您想检查结构化数据的有效性 您可以在 Rich Results Test - Google Search Console 页面的代码部分输入整个脚本< em>(而不是产品页面网址)。
一些有用的链接:
相关答案:
关于wordpress - 如何在 WooCommerce 中的产品结构化数据 (Schema.org) 中添加产品图像和描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66397008/