WooCommerce:添加产品架构属性 ean/identifier_exists

问题描述 投票:0回答:2

我使用此代码片段在 Woocommerce 的产品架构中显示 GTIN 的 ean 值:

add_filter( 'woocommerce_structured_data_product', 'filter_woocommerce_structured_data_product', 10, 2 ); 

function filter_woocommerce_structured_data_product( $markup, $product ) { 
if ( empty( $markup[ 'gtin8' ] ) ) {
    $markup[ 'gtin8' ] = get_post_meta( $product->get_id(), 'ean', true );
}

return $markup;
}

这可行,但我需要为没有自定义字段 ean 设置的产品设置“identifier_exists”标记。如何修改我的代码片段以在标记中显示 ean 值(如果存在),并将identifier_exists 属性 = false 添加到没有 ean 的产品?

php wordpress woocommerce schema product
2个回答
0
投票

尝试以下操作:

add_filter( 'woocommerce_structured_data_product', 'custom_schema', 99, 2 );
function custom_schema( $markup, $product ) {
    $value = $product->get_meta( 'ean' );
    $length = strlen($value);

    if ( ! empty($value) ) {
        $markup['identifier_exists'] = true;
        $markup['gtin'.$length]      = $value;
    } else {
        $markup['identifier_exists'] = false;
    }
    return $markup;
}

代码位于活动子主题(或活动主题)的functions.php文件中。


-1
投票

gtin
字段必须根据其长度进行设置。
在这里您将找到包含所有可用字段的完整文档。

gtin
必须是文本类型(非数字)

最后,

gtin
字段是可选的。 如果您的产品没有 EAN 代码 (或任何其他标识符) 您可以不设置
gtin

即使您将

identifier_exists
字段设置为 nofalse,您仍然会看到 “未提供全局标识符(例如,gtin、mpn、isbn)(可选)” 警告。你可以忽略它。事实上,文档中没有报告。

您可以在这里做一些测试:https://search.google.com/test/rich-results

// set the gtin in the structured data of the product
add_filter( 'woocommerce_structured_data_product', 'custom_schema', 99, 2 );
function custom_schema( $markup, $product ) {
    // get the product identifier
    $ean = get_post_meta( $product->get_id(), 'ean', true );
    // set gtin based on length
    switch ( strlen($ean) ) {
        case 8:
            $markup['gtin8'] = (string)$ean;
            break;
        case 12:
            $markup['gtin12'] = (string)$ean;
            break;
        case 13:
            $markup['gtin13'] = (string)$ean;
            break;
        case 14:
            $markup['gtin14'] = (string)$ean;
            break;
        default:
            $markup['identifier_exists'] = 'no';
            break;
    }
    return $markup;
}

代码已经过测试并且可以工作。将其添加到您活动主题的functions.php中。

相关答案:

© www.soinside.com 2019 - 2024. All rights reserved.