了解如何通过将产品的品牌添加到 WooCommerce 中的结构化数据(架构)来修复 Google Search Console 警告未填写字段“brand”。
这是一个易于遵循的教程,不需要任何新插件。 我们将使用一些标准的 WooCommerce 功能将品牌分配给产品,并且我们将编写一些 PHP 将品牌注入网站的结构化数据中。
请先确保你使用的是子主题,以免升级时文件被覆盖,并且可以编辑 functions.php。
创建品牌Brand产品属性
如何创建属性
修改产品模式
functions-brand-schema.php
<?php
/**
* 添加产品品牌数据结构(WPT_PBS)
*
*/
// Block direct access.
defined('WPINC') || die();
/**
* 如果您使用了不同的产品属性,例如“Marque”而不是“Brand”,请更改。
*/
const WPT_PBS_BRAND_ATTRIBUTE = 'pa_brand';
// const WPT_PBS_BRAND_ATTRIBUTE = 'pa_marque';
// const WPT_PBS_BRAND_ATTRIBUTE = 'pa_marca';
function add_brand_to_product_schema($data) {
if (!is_array($data)) {
// If $data isn't an array, don't do anything.
} elseif (empty($product = wc_get_product())) {
// Don't do anything.
} elseif (!is_array($brands = wc_get_product_terms($product->get_id(), WPT_PBS_BRAND_ATTRIBUTE, array('fields' => 'names')))) {
// This product has no brands associated with it.
} elseif (empty($brands)) {
// This product has zero brands associated with it.
} elseif (count($brands) == 1) {
// This product has exactly one brand associated with it.
$data['brand'] = array('@type' => 'Brand', 'name' => $brands[0]);
} else {
// This product has multiple brands associated with it.
$data['brand'] = array();
foreach ($brands as $brand) {
$data['brand'][] = array('@type' => 'Brand', 'name' => $brand);
}
}
return $data;
}
add_filter('woocommerce_structured_data_product', 'add_brand_to_product_schema');
在这里所做的就是挂钩一个标准的WooCommerce过滤器 woocommerce_structured_data_product ,它根据返回结构化产品数据的数组 Schema.org产品规格.
接下来,打开子主题的functions.php并将以下内容粘贴到其中,以引入我们的新功能。
// WP教程:将“品牌”添加到产品架构中
require_once dirname(__FILE__) . '/functions-brand-schema.php';
验证品牌模式
打开新的浏览器选项卡,并转到结构化数据测试工具。粘贴与品牌相关联的单个产品页面的URL。
如果你正在使用页面缓存插件,那么你应该刷新缓存,以确保你不会意外地验证页面的旧版本.