Skip to content

Instantly share code, notes, and snippets.

@robindevitt
Created October 28, 2022 05:49
Show Gist options
  • Save robindevitt/47970cbccc4f3bedf7cffc10d3025c92 to your computer and use it in GitHub Desktop.
Save robindevitt/47970cbccc4f3bedf7cffc10d3025c92 to your computer and use it in GitHub Desktop.
<?php
// Display a custom text under cart item name in cart page
add_action( 'woocommerce_before_calculate_totals', 'name_on_cart_item', 10, 1 );
function name_on_cart_item ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set the lineItemCount count to start at 1.
$lineItemCount = 1;
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get the product name (Added Woocommerce 3+ compatibility)
$original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;
if ( 1 === $lineItemCount ) { // If the product is the first product in the cart.
$shortcode = do_shortcode( "[gravityview id='1471']" );
$item_name = '<div class="item-shipping-class">' . $shortcode . '</div>' . $original_name;
} elseif ( 2 === $lineItemCount ) { // If the product is the second product in the cart.
$shortcode = do_shortcode( "[gravityview id='1569']" );
$item_name = '<div class="item-shipping-class">' . $shortcode . '</div>' . $original_name;
} else { // If the product is the 3rd+ in the cart.
$item_name = $original_name;
}
// Set the new name
if ( method_exists( $product, 'set_name' ) ) {
$product->set_name( $item_name );
} else {
$product->post->post_title = $item_name;
}
// Increase teh index count.
$lineItemCount ++;
} // End of each item in the cart.
} // End of name_on_cart_item.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment