在WooCommerce中将产品SKU添加到购物车项目名称之前

时间:2019-09-19 作者:Juraj

我有一段代码,在cart、mini cart和checkout中的cart item name之后添加产品SKU:

function show_sku_in_cart_items( $item_name, $cart_item, $cart_item_key ) {
    // The WC_Product object
    $product = $cart_item[\'data\'];

    // Get the  SKU
    $sku = $product->get_sku();

    // When sku doesn\'t exist
    if ( empty( $sku ) ) 
        return $item_name;

    // Add the sku

    if ( is_cart() ) {
         $item_name .= \'<br><small class="product-sku">\' . \'<span class="sku-title">\' . __( "SKU: ", "woocommerce") . \'</span>\' . $sku . \'</small>\';
    } else {
        $item_name .= \'<small class="product-sku">\' . $sku . \'</small>\';
    }

    return $item_name;
}

add_filter( \'woocommerce_cart_item_name\', \'show_sku_in_cart_items\', 99, 3 );
但我需要在购物车项目名称之前添加此项。

1 个回复
最合适的回答,由SO网友:LoicTheAztec 整理而成

您只需通过这种方式更改一点代码,即可获得SKUbefore 产品名称:

function show_sku_in_cart_items( $item_name, $cart_item, $cart_item_key ) {
    // The WC_Product object
    $product = $cart_item[\'data\'];

    // Get the  SKU
    $sku = $product->get_sku();

    // When SKU doesn\'t exist
    if ( empty( $sku ) ) 
        return $item_name;

    // Add SKU before
    if ( is_cart() ) {
        $item_name = \'<small class="product-sku">\' . \'<span class="sku-title">\' . __( "SKU: ", "woocommerce") . \'</span>\' . $sku . \'</small><br>\' . $item_name;
    } else {
        $item_name = \'<small class="product-sku">\' . $sku . \'</small>\' . $item_name;
    }

    return $item_name;
}

add_filter( \'woocommerce_cart_item_name\', \'show_sku_in_cart_items\', 99, 3 );

相关推荐