显示WooCommerce中的产品变化已添加到购物车消息中



在我的WooCommerce商店中,当添加了可变产品时,我将用户留在产品页面上。

成功通知消息显示产品标题以及通用附属物,但我希望它显示出具有诸如So的通知中的产品标题:

"男装大小:小"已添加到您的购物车中。

而不是:

"男装大衣"已添加到您的购物车中。

当前运行WooCommerce 3.3.1和WP 4.9。

谢谢

此代码是动态的,因此适用于添加到变量产品中的任何数量的属性。它会像往常一样处理简单的产品。

function modify_wc_add_to_cart_message( $message, $products ) {
    $attribute_label = '';
    $titles = array();
    $count  = 0;
    foreach ( $products as $product_id => $qty ) {
        $product = wc_get_product( $product_id );
        if( $product->is_type( 'variable' ) ) {
            foreach( $product->get_variation_attributes() as $attribute_name => $attribute_values ) {
                if( isset( $_REQUEST['attribute_' . strtolower( $attribute_name )] ) ) {
                    if( in_array( $_REQUEST['attribute_' . strtolower( $attribute_name )], $attribute_values ) ) {
                        if( ! empty( $attribute_label ) )
                            $attribute_label .= ', ';
                        $attribute_label .= $attribute_name . ' : ' . $_REQUEST['attribute_size'];
                    }
                }
            }
        }
        $titles[] = ( $qty > 1 ? absint( $qty ) . ' × ' : '' ) . sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) . ( ! empty( $attribute_label ) ? ' - ' . $attribute_label : '' ) ) ;
        $count += $qty;
    }
    $titles     = array_filter( $titles );
    $added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
    if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
        $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
        $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ), esc_html( $added_text ) );
    } else {
        $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View cart', 'woocommerce' ), esc_html( $added_text ) );
    }
    return $message;
}
add_filter( 'wc_add_to_cart_message_html', 'modify_wc_add_to_cart_message', 10, 2 );

上述代码中存在错误,其中引用" attribute_ize" - 它适用于op,因为这实际上是该变量的名称,但是如果您将其用于任何内容否则,整行必须是:

$attribute_label .= $attribute_name . ' : ' . $_REQUEST['attribute_' . strtolower( $attribute_name )];

最新更新