Как отобразить один атрибут на странице корзины?
Привет, нашел код для этой задачи но почему то он не отображает атрибуты которые я только что создал. А вот старые отображает. Товар вместе с атрибутами добавлялись через импорт , может в этом дело? Не пойму откуда копать начать.
Код ниже, для добавления конкретного атрибута меняю attribute_name на нужный мне (например pa_kozi) и атрибут видно в корзине, но любой вновь созданный атрибут отображаться не хочет :(
Подскажите плз
function isa_woo_cart_attribute_values( $cart_item, $cart_item_key ) { $item_data = $cart_item_key['data']; $attributes = $item_data->get_attributes(); if ( ! $attributes ) { return $cart_item; } $out = $cart_item . '<br />'; $count = count( $attributes ); $i = 0; foreach ( $attributes as $attribute ) { // skip variations if ( $attribute->get_variation() ) { continue; } $name = $attribute->get_name(); if ( $attribute->is_taxonomy() ) { if ($name !== 'attribute_name') { continue; } $product_id = $item_data->get_id(); $terms = wp_get_post_terms( $product_id, $name, 'all' ); // get the taxonomy $tax = $terms[0]->taxonomy; // get the tax object $tax_object = get_taxonomy($tax); // get tax label if ( isset ( $tax_object->labels->singular_name ) ) { $tax_label = $tax_object->labels->singular_name; } elseif ( isset( $tax_object->label ) ) { $tax_label = $tax_object->label; // Trim label prefix since WC 3.0 $label_prefix = 'Product '; if ( 0 === strpos( $tax_label, $label_prefix ) ) { $tax_label = substr( $tax_label, strlen( $label_prefix ) ); } } $out .= $tax_label . ': '; $tax_terms = array(); foreach ( $terms as $term ) { $single_term = esc_html( $term->name ); array_push( $tax_terms, $single_term ); } $out .= implode(', ', $tax_terms); if ( $count > 1 && ( $i < ($count - 1) ) ) { $out .= ', '; } $i++; // end for taxonomies } else { // not a taxonomy $out .= $name . ': '; $out .= esc_html( implode( ', ', $attribute->get_options() ) ); if ( $count > 1 && ( $i < ($count - 1) ) ) { $out .= ', '; } $i++; } } echo $out; } add_filter( 'woocommerce_cart_item_name', isa_woo_cart_attribute_values, 10, 2 ); |
function isa_woo_cart_attribute_values( $cart_item, $cart_item_key ) { $item_data = $cart_item_key['data']; $attributes = $item_data->get_attributes(); if ( ! $attributes ) { return $cart_item; } $out = $cart_item . '<br />'; $count = count( $attributes ); $i = 0; foreach ( $attributes as $attribute ) { // skip variations if ( $attribute->get_variation() ) { continue; } $name = $attribute->get_name(); if ( $attribute->is_taxonomy() ) { if ($name !== 'attribute_name') { continue; } $product_id = $item_data->get_id(); $terms = wp_get_post_terms( $product_id, $name, 'all' ); // get the taxonomy $tax = $terms[0]->taxonomy; // get the tax object $tax_object = get_taxonomy($tax); // get tax label if ( isset ( $tax_object->labels->singular_name ) ) { $tax_label = $tax_object->labels->singular_name; } elseif ( isset( $tax_object->label ) ) { $tax_label = $tax_object->label; // Trim label prefix since WC 3.0 $label_prefix = 'Product '; if ( 0 === strpos( $tax_label, $label_prefix ) ) { $tax_label = substr( $tax_label, strlen( $label_prefix ) ); } } $out .= $tax_label . ': '; $tax_terms = array(); foreach ( $terms as $term ) { $single_term = esc_html( $term->name ); array_push( $tax_terms, $single_term ); } $out .= implode(', ', $tax_terms); if ( $count > 1 && ( $i < ($count - 1) ) ) { $out .= ', '; } $i++; // end for taxonomies } else { // not a taxonomy $out .= $name . ': '; $out .= esc_html( implode( ', ', $attribute->get_options() ) ); if ( $count > 1 && ( $i < ($count - 1) ) ) { $out .= ', '; } $i++; } } echo $out; } add_filter( 'woocommerce_cart_item_name', isa_woo_cart_attribute_values, 10, 2 );
Дополнительно:
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

В вашем коде есть несколько проблем. Главная: фильтр
woocommerce_cart_item_nameпринимает вторым аргументом массив$cart_item, а не ключ. У вас переменные названы наоборот, поэтому код легко начинает работать непредсказуемо.Для вывода одного конкретного атрибута в корзине лучше использовать фильтр
woocommerce_get_item_data. Он предназначен именно для дополнительных строк под названием товара в корзине и checkout.add_filter( 'woocommerce_get_item_data', 'site_show_cart_attribute', 10, 2 ); function site_show_cart_attribute( $item_data, $cart_item ) { if ( empty( $cart_item['data'] ) || ! $cart_item['data'] instanceof WC_Product ) { return $item_data; } $product = $cart_item['data']; $parent_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id(); $taxonomy = 'pa_kozi'; $terms = wc_get_product_terms( $parent_id, $taxonomy, [ 'fields' => 'names' ] ); if ( ! empty( $terms ) ) { $item_data[] = [ 'key' => wc_attribute_label( $taxonomy ), 'value' => esc_html( implode( ', ', $terms ) ), ]; } return $item_data; }
Если новые атрибуты не отображаются, проверьте не название в админке, а slug таксономии. Глобальные атрибуты WooCommerce имеют вид
pa_slug. Например атрибут «Кожа» может быть неpa_kozi, аpa_kozhaили другой slug, заданный при создании.Также проверьте:
Для быстрой диагностики выведите атрибуты товара временно в лог:
error_log( print_r( array_keys( $product->get_attributes() ), true ) );
Так вы увидите реальные ключи атрибутов и подставите правильный taxonomy slug.