Reputation: 599
I have one product with multiple variants, and I'd like to display all the variants (not attributes) with their relative SKU in the additional informations tab, like so:
Based on Display in additional information tab, some product settings custom fields values I added the code to the informations tab of my product:
Where $custom_field1
should be the result of the attribute's name + the SKU and the GTIN (added by this plugin):
Notes:
$gtin = $product->get_meta('_wpm_gtin_code');
Upvotes: 1
Views: 1021
Reputation: 29614
You could use the following, it will add extra row. Explanation via comment tags added in the code.
function filter_woocommerce_display_product_attributes( $product_attributes, $product ) {
// Variable product
if ( $product->is_type('variable' ) ) {
// Get childIDs in an array
$children_ids = $product->get_children();
// Output
$output = '';
// Loop
foreach ( $children_ids as $child_id ) {
// Get product
$variation = wc_get_product( $child_id );
// Get variation name
$variation_name = ( $name = implode( ' / ', $variation->get_variation_attributes() ) ) ? $name : esc_html__( 'N/A', 'woocommerce' );
// Get product SKU
$get_sku = ( $sku = $variation->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' );
// Get GTIN code
$gtin_value = ( $gtin = $variation->get_meta( '_wpm_gtin_code' ) ) ? $gtin : esc_html__( 'N/A', 'woocommerce' );
// Concatenate string
$output .= '<p>' . $variation_name . ' - EAN: ' . $get_sku . ' GTIN: ' . $gtin_value . '</p>';
}
// Add
$product_attributes[ 'custom_field' ] = array(
'label' => __( 'Custom field', 'woocommerce' ),
'value' => $output,
);
}
return $product_attributes;
}
add_filter( 'woocommerce_display_product_attributes', 'filter_woocommerce_display_product_attributes', 10, 2 );
Result: (GTIN not available because I don't use that plugin)
Related:
Additional question
To remove a table row you can simply use:
unset ( $product_attributes['weight'] );
But it can also be the other way around where we will indicate via this piece of code which table rows we want to keep
// For debugging purposes - uncomment if needed
//echo '<pre>', print_r( $product_attributes, 1 ), '</pre>';
// Add the rows you want to keep, you can add multiple rows, separated by a comma
$rows_to_keep = array ( 'weight', 'dimensions' );
// Loop
foreach ( $product_attributes as $key => $product_attribute ) {
// Not in array 'rows to keep'
if ( ! in_array ( $key, $rows_to_keep ) ) {
// Remove
unset ( $product_attributes[$key] );
}
}
Both pieces of code can be applied in my above answer
Upvotes: 2