WooCommerce 的订单页面内容繁多,如果直接打印后台页面,想必是惨不忍睹,还好有一款免费插件可以解决这个问题——WooCommerce Print Invoices & Delivery Notes,这个插件的好处是通过修改模版,你可以打印订单中的任何内容,漂亮的打印出来。

关于该插件的使用不再赘述,本文介绍如何修改打印模版,加入自己需要的数据。比如,加入产品缩略图和产品分类,效果如下图所示

print-order

首先,获取缩略图和产品分类数据

在主题的 functions.php 中加入如下代码

add_filter( 'wcdn_order_item_data', 'wcdn_print_image' );
function wcdn_print_image( $data ){
	//get image
	$img_id = get_post_thumbnail_id( $data['product_id'] );
	$img_url = wp_get_attachment_image_src($img_id);
	$img_url = $img_url[0];
	$data['image'] = $img_url;
	
	//get category
	$terms = get_the_terms( $data['product_id'], 'product_cat' );
	foreach ($terms as $term) {
            $data['category'][] = $term->name . ': ' . $term->description;
	}
	return $data;
}

修改打印模版

WooCommerce-delivery-notes/templates/print/print-delivery-note.php 复制到主题目录/WooCommerce/print/下,打开该文件修改。

<div id=”order-items”> 是订单列表的开始,首先把表头修改一下,加入了我需要的 Category

<thead>
    <tr>
        <th class="product-label" width="50%" ><?php _e('Product', 'WooCommerce-delivery-notes'); ?></th>
        <th class="product-label" width="30%"><?php _e('Category', 'WooCommerce-delivery-notes'); ?></th>
        <th class="quantity-label" width="10%"><?php _e('Quantity', 'WooCommerce-delivery-notes'); ?></th>
        <th class="totals-label" width="10%"><?php _e('Totals', 'WooCommerce-delivery-notes'); ?></th>
    </tr>
</thead>

然后修改表单内容,刚刚在主题 funcitons.php 中已经将额外的数据传过来,这些数据由下面这个函数获取

$items = wcdn_get_order_items();

接下来要做的就是调用这些数据

<?php $items = wcdn_get_order_items(); if( sizeof( $items ) > 0 ) : foreach( $items as $item ) : ?><tr>
        <td class="description"><?php echo $item['name']; ?>
            <?php echo $item['meta']; ?>
            <dl class="meta">
                <?php if( !empty( $item['sku'] ) ) : ?>
                    <dt><?php _e( 'SKU:', 'WooCommerce-delivery-notes' ); ?></dt><dd><?php echo $item['sku']; ?></dd><?php endif; ?>
                <?php if( !empty( $item['weight'] ) ) : ?>
                    <dt><?php _e( 'Weight:', 'WooCommerce-delivery-notes' ); ?></dt><dd><?php echo $item['weight']; ?><?php echo get_option('WooCommerce_weight_unit'); ?></dd><?php endif; ?>
            </dl>
        </td>
        <td class="quantity"><?php echo $item['quantity']; ?></td>
        <td class="price"><?php echo $item['price']; ?></td>
</tr><?php endforeach; endif; ?>