Reputation: 63
I am working on an invoice system for my woocommerce shop.
I am using a plugin that adds weight unit custom field to all products(simple and for each variable of variant product)
I had managed to add the quantity unit column to the invoice plugin, and for simple products, I manage to fetch the field.
On the other hand, this method is not working for fetching the unit of a variant in a variable product.
The following code is what I use to get the custom field.
Please help
/**
* Adds line item quantity to columns data array.
*
* @param array $data line item data.
* @param int $item_id item ID.
* @param object $item item object.
*/
public function add_quantity_column_data( &$data, $item_id, $item ) {
$product_id = $item->get_product_id();
$quantity_suffix = get_post_meta( $product_id, '_upw_quantity_suffix', true);
$quantity_suffix_sep = " ";
$data['quantity'] = $item['qty'] . $quantity_suffix_sep . $quantity_suffix
}
the custom field key is _upw_quantity_suffix
.
Upvotes: 4
Views: 1258
Reputation: 253784
To handle product variations custom field too, you can try this revisited code version:
/**
* Adds line item quantity to columns data array.
*
* @param array $data line item data.
* @param int $item_id item ID.
* @param object $item WC_Order_Item_Product Object.
*/
public function add_quantity_column_data( &$data, $item_id, $item ) {
$product = $item->get_product();
$qty_suffix = $product->get_meta( '_upw_quantity_suffix' );
$sepatator = ' ';
if ( ! empty($qty_suffix) ) {
$data['quantity'] = $item['qty'] . $sepatator . $qty_suffix;
}
}
It should work.
Or you can also try:
/**
* Adds line item quantity to columns data array.
*
* @param array $data line item data.
* @param int $item_id item ID.
* @param object $item WC_Order_Item_Product Object.
*/
public function add_quantity_column_data( &$data, $item_id, $item ) {
$product = $item->get_product();
$qty_suffix = $product->get_meta( '_upw_quantity_suffix' );
if ( empty($qty_suffix) ) {
$product = wc_get_product( $item->get_product_id() );
$qty_suffix = $product->get_meta( '_upw_quantity_suffix' );
}
$sepatator = ' ';
if ( ! empty($qty_suffix) ) {
$data['quantity'] = $item['qty'] . $sepatator . $qty_suffix;
}
}
Upvotes: 4