Как отобразить один атрибут на странице корзины?

Ссылка скопирована
1 ответ

Привет, нашел код для этой задачи но почему то он не отображает атрибуты которые я только что создал. А вот старые отображает. Товар вместе с атрибутами добавлялись через импорт , может в этом дело? Не пойму откуда копать начать.
Код ниже, для добавления конкретного атрибута меняю 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 );

Дополнительно:

Нужно решить такую задачу?

Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

Заказать помощь
Лучший ответ
1
Юрий Linux Ответ

В вашем коде есть несколько проблем. Главная: фильтр 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;
}

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, заданный при создании.

Также проверьте:

  • атрибут добавлен именно к товару, а не только создан в Товары → Атрибуты;
  • после импорта у товара есть термины этого атрибута;
  • атрибут является глобальным taxonomy-атрибутом, а не кастомным текстовым атрибутом товара;
  • для вариативного товара данные могут лежать у родительского товара, а не у вариации.

Для быстрой диагностики выведите атрибуты товара временно в лог:

error_log( print_r( array_keys( $product->get_attributes() ), true ) );

error_log( print_r( array_keys( $product->get_attributes() ), true ) );

Так вы увидите реальные ключи атрибутов и подставите правильный taxonomy slug.

Другие ответы (0)

Пока нет других ответов. Будьте первым, кто поможет автору.

Ответить на вопрос

комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вам также может быть интересно