Skip to content

Instantly share code, notes, and snippets.

@marcusig
Created December 22, 2022 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusig/efc50f64cfeac681bf248f9d91c045cb to your computer and use it in GitHub Desktop.
Save marcusig/efc50f64cfeac681bf248f9d91c045cb to your computer and use it in GitHub Desktop.
List all product attributes with the variation attributes
<?php
add_filter( 'woocommerce_get_item_data', 'wall_display_custom_item_data', 10, 2 );
function wall_display_custom_item_data( $cart_item_data, $cart_item ) {
$product = $cart_item['data'];
$attributes = wall_format_attributes( $product );
if ( ! $attributes ) {
return $cart_item_data;
}
$cart_item_data[] = array(
'name' => __( 'Attributes', 'woocommerce' ),
'value' => $attributes
);
return $cart_item_data;
}
// Save and Display the order item weight (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'wall_display_order_item_data', 20, 4 );
function wall_display_order_item_data( $item, $cart_item_key, $values, $order ) {
$attributes = wall_format_attributes( $item->get_product() );
if ( $attributes ) {
$item->update_meta_data( __( 'Attributes', 'woocommerce' ), $attributes );
}
}
function wall_format_attributes( $product ) {
$attributes = $product->get_attributes();
$out = '';
foreach ( $attributes as $attribute ) {
if ( $attribute['is_taxonomy'] ) {
// skip variations
if ( $attribute['is_variation'] ) {
continue;
}
// backwards compatibility for attributes which are registered as taxonomies
$product_id = $product->get_id();
$terms = wp_get_post_terms( $product_id, $attribute['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->name) ) {
$tax_label = $tax_object->labels->name;
} elseif ( isset( $tax_object->label ) ) {
$tax_label = $tax_object->label;
}
foreach ( $terms as $term ) {
$out .= '<div>' . '<strong>' . $tax_label . '</strong>: ';
$out .= $term->name . '</div>';
}
} else {
// not a taxonomy
$out .= '<div>' . '<strong>' . $attribute['name'] . '</strong>: ';
$out .= $attribute['value'] . '</div>';
}
}
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment