Based on WooCommerce variable products: Display some variations values in an HTML table code answer, I have this table showing correctly, but I only want the attribute columns to show if they exist, how can I alter this to do so?
E.g. If there are any variations that have 'Techonology' as an option then show the 'Technology' column, if not hide it.
add_action( 'woocommerce_after_single_product_summary', 'custom_table_after_single_product' );
function custom_table_after_single_product(){
global $product;
if( ! $product->is_type('variable')) return;
$available_variations = $product->get_available_variations();
if( count($available_variations) > 0 ){
$output = '<table>
<thead>
<tr>
<th>'. __( 'Image', 'woocommerce' ) .'</th>
<th>'. __( 'SKU', 'woocommerce' ) .'</th>
<th>'. __( 'Colour', 'woocommerce' ) .'</th>
<th>'. __( 'Technology', 'woocommerce' ) .'</th>
<th>'. __( 'Positive/Negative', 'woocommerce' ) .'</th>
</tr>
</thead>
<tbody>';
foreach( $available_variations as $variation ){
// Get an instance of the WC_Product_Variation object
$product_variation = wc_get_product($variation['variation_id']);
$output .= '
<tr>
<td>'. $product_variation->get_image('snippets') .'</td>
<td>'. $product_variation->get_sku() .'</td>
<td>'. $product_variation->get_attribute('pa_colour_range') .'</td>
<td>'. $product_variation->get_attribute('pa_technology') .'</td>
<td>'. $product_variation->get_attribute('pa_posneg') .'</td>
</tr>';
}
$output .= '
</tbody>
</table>';
echo $output;
}
}
Try the following, that will display each table column only if there are values for it:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.