kilbot / WooCommerce-POS

:bangbang: All development now at https://github.com/wcpos.
http://wcpos.com
GNU General Public License v3.0
353 stars 125 forks source link

How to access item meta values on product receipt #201

Closed Elextric closed 5 years ago

Elextric commented 5 years ago

I am trying to add a piece of meta information to the printed receipt, which is displayed on the e-mailed receipt. Yet I can not find a way to do this.

I've located the code, (in print/tmpl-receipt.php) responsible for the item details in the receipt

  {{#each line_items}}
    <tr>
      <td class="product">
        {{name}}
        {{#with meta}}
        <dl class="meta">
          {{#each []}}
          <dt>{{label}}:</dt>
          <dd>{{value}}</dd>
          {{/each}}
        </dl>
        {{/with}}            
      </td>

Assuming in: wp_woocommerce_order_itemmeta table,

I have a meta_key called _xyz_abc

how to I display the key value for _xyz_abc on the receipt?

I can not figure out how to access the meta data for the item from within the printed receipt. The is already included on the e-mail receipt, but is not displaying on the printed receipt.

Any pointers appreciated.

kilbot commented 5 years ago

Hi @Elextric, I recently answered this question on StackOverflow.

Meta data with an underscore at the front is considered private, so the POS strips out this data by default. WooCommerce can often have a dozen private meta data attached to each order item (depending on which plugins you are using), so displaying them all by default is not desirable either.

Ideally a plugin should store meta data which is meant for display, eg; Gift Card codes, without the underscore. If they do this the code would appear in emails, POS templates and the WP Admin automatically.

In the next version of WooCommerce POS will have the ability to inspect item meta, including private meta, so this may also help in the near future.

In the meantime you could use a custom function to add the meta to the WC REST API response, eg:

function my_custom_wc_rest_shop_order_object($response)
{
  if (function_exists('is_pos') && is_pos()) {
    $data = $response->get_data();
    if (is_array($data['line_items'])) : foreach ($data['line_items'] as &$line_item) :
      if ($value = wc_get_order_item_meta($line_item['id'], '_xyz_abc')) {
        $line_item['meta_data'][] = new WC_Meta_Data(array(
          'id' => '',
          'key' => 'Label (no underscore)',
          'value' => $value,
        ));
      }
    endforeach; endif;
    $response->set_data($data);
  }
  return $response;
}
add_filter('woocommerce_rest_prepare_shop_order_object', 'my_custom_wc_rest_shop_order_object');
Elextric commented 5 years ago

Paul thank you! I've spent days trying to figure this out. I will try this solution today. Really appreciate the help.