0

We are developing a B2B shop with WooCommerce.

I want to show the SKU and the product dimensions underneath the product title in the cart.

This is what I have right now:

add_filter( 'woocommerce_cart_item_name', 'add_sku_in_cart', 20, 3);
function add_sku_in_cart( $title, $values, $cart_item_key ) {
$sku = $values['data']->get_sku();
$dimensions = $values['data']->get_dimensions();
return $sku ? $title . sprintf(" <br><span class='articlenumber'>Artikelnummer: %s</span>", $sku) : $title;
return $dimensions ? $title . sprintf(" <br><span class='measurements'>Maße: %s</span>", $dimensions) : $title;
}

Someone already told me that 2 returns won´t work and that I need a string. But since I am very new to PHP, I don´t know how to do it. Could someone please help me with that?

Thank you in advance and have a great day.

1

Each function in PHP can have 0 or 1 return statement. It is important to know that a return will also end the execution of a function. You can read more about that in the official PHP docs. For the other part, you need to make one string out of multiple strings, this is called concatenation and already used in your code, read more about it here.

Applying those principles (and using proper if instead of ternary for better readability), your code turns into:

add_filter( 'woocommerce_cart_item_name', 'add_sku_in_cart', 20, 3);
function add_sku_in_cart( $title, $values, $cart_item_key ) {
    $sku = $values['data']->get_sku();
    $dimensions = $values['data']->get_dimensions();
    if ($sku) {
        $title = $title . sprintf(" <br><span class='articlenumber'>Artikelnummer: %s</span>", $sku);
    }
    if ($dimensions) {
        $title = $title . sprintf(" <br><span class='measurements'>Maße: %s</span>", $dimensions);
    }
    return $title;
}
  • This code gives me some errors, VSC is pointing out $title = $title . sprintf(" <br><span class='articlenumber'>Artikelnummer: %s</span>", $sku) : $title; and $title = $title . . sprintf(" <br><span class='measurements'>Maße: %s</span>", $dimensions) : $title; as source of the error. In short: It unfortunately doesn´t work. – Marvin Klempert Nov 8 at 11:58
  • @MarvinKlempert Sorry, copy/paste errors. Should work now, I forgot to remove these parts of the ternary (foo ? a : b) when changing to long if – kero Nov 8 at 12:15
  • 1
    This was it. Now the code works. Thank you very much. I will be doing a basic php course soon, so I really understand the basics. – Marvin Klempert Nov 8 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.