1

I want to display the price and the subtotal of a cart item in the table cell of the product name. The reason is, that I need an other view on mobile phones. For desktop viewports the table cells for price and subtotal should stay. So I want to add an extra version for mobile and hide it on desktop.

I found the hook woocommerce_after_cart_item_name and I know how to add content below the product name.

Here's the code I tried: (not successful so far)

    add_filter('woocommerce_after_cart_item_name','copy_cart_product_price',10,3);
function copy_cart_product_price($cart_item, $cart_item_key){

    $cart_price_subtotal = sprintf(
        '<p class="cart-price">6,90&euro;</p>',
        '<p class="cart-subtotal">13,80&euro;</p>'
    );

    $cart_item .= $cart_price_subtotal;
    return $cart_item;

}

My problem is, that I don't know how to get the price.

I guess I have to work with these two filters:

For the price:

echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); // PHPCS: XSS ok.

For the subtotal:

echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // PHPCS: XSS ok.

But how can I show/use these filters with my snippet?

And is there a way to only show the subtotal if there are 2 or more of pieces one item in the cart?

Cray
  • 5,307
  • 11
  • 70
  • 166

1 Answers1

2

I believe you mean this? explanation with comment added in the code

function action_woocommerce_after_cart_item_name( $cart_item, $cart_item_key ) {
    // Price
    $price = $cart_item['data']->get_price();

    // Line subtotal
    $subtotal = $cart_item['line_subtotal'];

    // Quantity
    $quantity = $cart_item['quantity'];

    echo '<p class="cart-price">' . wc_price( $price )  . '</p>';

    if ( $quantity >= 2 ) {
        echo '<p class="cart-subtotal">' . wc_price( $subtotal ) . '</p>';
    }
}
add_action( 'woocommerce_after_cart_item_name', 'action_woocommerce_after_cart_item_name', 10, 2 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50