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.
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.
Share Improve this question asked Nov 8, 2019 at 11:30 Marvin KlempertMarvin Klempert 31 bronze badge1 Answer
Reset to default 1Each 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;
}