Site icon Hip-Hop Website Design and Development

Add custom attribute to product’s HTML to woocommerce cart page

I’m trying to add a data-attribute to WooCommerce’s cart page.

The cart page populates a table with each row being a product that has been added to the cart.

I’m able to add a data attribute into the HTML for this row like so:

/wp-content/plugins/woocommerce/templates/cart/cart.php

<?php
  // For each item in cart
  foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    // Get product
    $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

    // Get custom attribute
    $foobar = $_product->get_attribute( 'myCustomAttribute' );
    $foobar == true ? $foo = "true" : $foo = "false";
    ?>

    // Add table row with custom attribute as a data attribute
    <tr data-foo=<?php echo "$foo"; ?>>...Content in here</tr>
  <?php 
  }

I know this is bad practise as it’ll be overwritten when the plugin is updated.

I’m trying to add the same functionality into my template’s functions.php file but after looking through the WooCommerce support docs I can’t see anything that would help.

Any ideas?