Below is the code which give output as " SKU:1018 SKU:1026 ". I am not able to get the desired output from this code please help
I want output like "SKU:1018,1026 "
<?php
$new= $order->get_items();
foreach ( $new as $item ) {
$product_id = $item['product_id'];
$prod = new WC_Product($product_id);
$sku=$prod->get_sku();
echo "SKU:".$sku." ";
}
?>
You should be able to get the desired output of SKU:1018,1026
with something like:
$prefix = "SKU:"
foreach ($new as $item) {
$product_id = $item['product_id'];
$prod = new WC_Product($product_id);
$sku = $prod->get_sku();
echo $prefix . $sku;
$prefix = ",";
}
This simply sets the initial prefix to SKU:
then, for each item, outputs that prefix followed by the item number. After the first one is output, it sets the prefix to ,
so that subsequent items will be preceded by that comma.
You want to display all SKUs against the string SKU:
.
And you are printing the string SKU
in the loop.
Rather than that, get all SKUs in an array and print it using implode() function.
<?php
$new= $order->get_items();
$skus = array();
foreach ( $new as $item ) {
$product_id = $item['product_id'];
$prod = new WC_Product($product_id);
$skus[] = $prod->get_sku();
}
echo "SKU:" . implode(',', $skus);
?>
It is always safe to use arrays for dealing multiple strings because, you can apply any complex logic with ease.
Again, if there is no data found, array code in the above example will simply print blank without causing any error.
Try this :-
<?php
$new= $order->get_items();
$txt = "SKU: ";
foreach ( $new as $item ) {
$product_id = $item['product_id'];
$prod = new WC_Product($product_id);
$sku=$prod->get_sku();
$txt .= $sku.", ";
}
$txt = rtrim(", ", $txt);
echo $txt;
?>
Try with the below code,Use implode to get the array value as comma seperated.
<?php
$new= $order->get_items();
foreach ( $new as $item ) {
$product_id = $item['product_id'];
$prod = new WC_Product($product_id);
$sku[]=$prod->get_sku();
}
$skulist=implode(",",$sku);
echo "SKU:".$skulist." ";
?>
Change the $sku
to $sku[]
, an array, and the
last line to
echo "SKU:".implode(",",$sku);