簡體   English   中英

顯示woocommerce中的產品變化已添加到購物車消息

[英]Show product variation in woocommerce Added to cart message

在我的WooCommerce商店中,將可變產品添加到購物車后,我讓用戶停留在產品頁面上。

成功通知消息顯示產品標題以及通用附件,但我希望它在通知中顯示產品標題的變化,如下所示:

“男士大衣-尺寸:小”已添加到您的購物車。

而不是:

“男士大衣”已添加到您的購物車。

當前正在運行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_size”-它適用於OP,因為它實際上是變量的名稱,但是如果您將其用於其他用途,則整行必須是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM