如何在添加到购物车消息中将 product_name 替换为 product_sku

How to replace product_name by product_sku on Add to cart message

默认情况下,此消息行将是:

Product product_name has been added to cart

我想把product_name改成product_sku 有什么办法吗?非常感谢!

注意:这是我用来编辑消息内容的代码,但它没有添加product_sku

add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_custom', 10, 2 );

function wc_add_to_cart_message_custom( $message, $products ) {
    if ( empty( $products ) ) {
        return $message;
    }

    foreach( $products as $product_id => $qty ) {
        $titles[] = get_the_title( $product_id );
    }

    $titles = array_filter( $titles );
    $added_text = sprintf( _n( 'product %s', 'product %s', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );
    $message = sprintf( '%s <img src="images/Success.svg" style="width: 24px"> <a style="font-weight: 800">Added: </a>%s', esc_html__( '', 'woocommerce' ), esc_html( $added_text ));

    return $message;
}

您可以收集产品的 SKU,而不是收集产品“名称”,即名称。

add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_custom', 10, 2 );

function wc_add_to_cart_message_custom( $message, $products ) {
    if ( empty( $products ) ) {
        return $message;
    }

    foreach( $products as $product_id => $qty ) {
        // get product object from ID
        $product = wc_get_product( $product_id );
        // add product SKU to array
        $skus[] = $product->get_sku();
         
    }

    $skus = array_filter( $skus );
    $added_text = sprintf( _n( 'product %s', 'product %s', sizeof( $skus ), 'woocommerce' ), wc_format_list_of_items( $skus ) );
    $message = sprintf( '%s <img src="images/Success.svg" style="width: 24px"> <a style="font-weight: 800">Added: </a>%s', esc_html__( '', 'woocommerce' ), esc_html( $added_text ));

    return $message;
}