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; ?>