Показать атрибуты вариации товара при добавлении в корзину сообщения в Woocommerce - PullRequest
0 голосов
/ 17 ноября 2018

В WooCommerce, когда кто-то добавляет продукт в корзину, отображается подтверждающее сообщение.Вместо того, чтобы показывать родителя, я хочу показать варианты, которые клиент поместил в свою корзину.

Я использую код Эндрю Шульца из ответа на Показать вариант продукта в woocommerceДобавлено в корзину сообщение Я думаю, что крючки или имена изменились, потому что происходит то, что "pa_subject" показывается, когда он должен сказать, например, "География".

Любые идеи, как это изменить?

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 );

scamp of return

1 Ответ

0 голосов
/ 17 ноября 2018

Да, код выдает некоторые ошибки, когда включена отладка:

Примечание: Неопределенный индекс: размер_ атрибута в ../wp-content/themes/storefront-child/functions.php в строке xxxx

По существу, с этой строкой:

$attribute_label .= $attribute_name . ' : ' . $_REQUEST['attribute_size'];

Кажется, этот код был создан для обработки пользовательского атрибута "size" вместо любого.

Он также отображает слаг атрибута woocommerce, начинающийся с "pa_" вместо имени метки таксономии атрибута:

enter image description here

Чтобы заставить его работать и отображать правильные имена меток атрибутов вместе со значениями их имен терминов, используйте следующую версию кода:

add_filter( 'wc_add_to_cart_message_html', 'change_add_to_cart_message', 10, 2 );
function change_add_to_cart_message( $message, $products ) {
    $titles = array();
    $count  = 0;

    foreach ( $products as $product_id => $qty ) {
        // Get the WC_Product object instance
        $product = wc_get_product( $product_id );
        if( $product->get_type() === 'variable' ) {
            $variation_attributes = array();
            foreach( $product->get_variation_attributes() as $taxonomy => $terms_slugs ) {
                $wc_attribute_name = wc_variation_attribute_name( $taxonomy );
                if( isset( $_REQUEST[$wc_attribute_name] ) ) {
                    if( in_array( $_REQUEST[$wc_attribute_name], $terms_slugs ) ) {
                        $term_name = get_term_by( 'slug', $_REQUEST[$wc_attribute_name], $taxonomy )->name;
                        $variation_attributes[] = wc_attribute_label( $taxonomy ) . ': ' . $term_name;
                    }
                }
            }
            $variation_attributes = implode(', ', $variation_attributes);
        }

        $titles[] = ( $qty > 1 ? absint( $qty ) . ' &times; ' : '' ) . sprintf( _x( '&ldquo;%s&rdquo;', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) . ( ! empty( $variation_attributes ) ? ' - ' . $variation_attributes : '' ) ) ;
        $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;
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

enter image description here


Для отображения только названий терминов без названия метки таксономии

Заменить в коде эту строку:

$variation_attributes[] = wc_attribute_label( $taxonomy ) . ': ' . $term_name;

этим:

$variation_attributes[] = $term_name;

Вы получите что-то вроде:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...