WooCommerce订单详情页显示商品总数量:代码植入位置咨询
Hey there! Let's figure out why your code isn't working and get that total product quantity showing up correctly on your order details page.
First: Fix the Filter Hook (Recommended, No Template Edits Needed)
The issue with your original code is that the woocommerce_order_items_table filter actually passes the HTML output of the order items table as the first parameter, not the order object directly. Your function wasn't returning modified content, which is why you saw no changes.
Here's the corrected code you can add to your theme's functions.php file (or a custom plugin for better maintainability):
add_filter( 'woocommerce_order_items_table', 'add_items_count_on_order_page', 10, 2 ); function add_items_count_on_order_page( $output, $order ) { // Build the HTML for the quantity row $quantity_row = '<tr class="product-total-quantity"> <th>' . esc_html__( 'Product Quantity', 'woocommerce' ) . '</th> <td>' . esc_html( $order->get_item_count() ) . '</td> </tr>'; // Insert the row right before the closing </tbody> tag of the order table $output = str_replace( '</tbody>', $quantity_row . '</tbody>', $output ); return $output; }
This method is better because it avoids modifying core WooCommerce templates—your changes won't get overwritten when WooCommerce updates.
If You Prefer Editing the Template File
If you want to edit the template directly (remember to copy the template to your theme directory first to prevent update losses), follow these steps:
- Copy
woocommerce/templates/order/order-details.phptoyour-theme-folder/woocommerce/order/order-details.php - Open the copied file and find the closing
</tbody>tag of the order table. - Insert your quantity row right before that closing tag, after the loop that renders individual order items.
Here's where to place it in the template:
<?php } // End of the order items loop ?> <!-- Add your total quantity row here --> <tr class="cart-subtotal"> <th><?php esc_html_e( 'Product Quantity', 'woocommerce' ); ?></th> <td><?php echo esc_html( $order->get_item_count() ); ?></td> </tr> </tbody>
Note: We added esc_html() to sanitize the output, which is a best practice for security.
Why Your Original Code Didn't Work
Your function was set up to accept $order as the only parameter, but the woocommerce_order_items_table filter expects the first parameter to be the table's HTML output. Since your function didn't return any modified content, the original table rendered without your changes.
内容的提问来源于stack exchange,提问作者Mariannemagic

