如何在WooCommerce近期订单后台小工具中正确添加billing_first_name字段
代码问题与修复方案
你代码存在4处错误,修改后即可正常显示billing_first_name字段:
- 语法错误:调用
get_billing_first_name()时缺少箭头的减号,错误写法$order>get_billing_first_name(),正确应为$order->get_billing_first_name() - 函数误用:
wc_get_order_status_name()仅用于转换订单状态为可读文本,不能用于处理订单金额、账单姓名这类非状态字段,对应位置删除该函数调用即可 - 逻辑错误:
if ( $order )判断的闭合位置错误,原代码在输出订单ID后就提前关闭了判断,后续调用$order的代码没有被包含在判断范围内 - 参数错误:订单查询的
post_status参数值All不符合WordPress规范,获取所有状态订单需改为any
修正后完整代码
/** * Add a widget to the dashboard. * */ function wc_orders_dashboard_widgets() { wp_add_dashboard_widget( 'wc_order_widget_id', // Widget slug. 'Cartlog Orders', // Title. 'wc_orders_dashboard_widget_function' // Display function. ); } add_action( 'wp_dashboard_setup', 'wc_orders_dashboard_widgets' ); /** * Pulls the order information to the dashboard widget. */ function wc_orders_dashboard_widget_function() { $args = array( 'post_type' => 'shop_order', 'post_status' => 'any', //获取所有状态订单,也可单独指定 wc-pending、wc-processing等状态 'posts_per_page' => 10 //调整展示的订单数量 ); $orders = get_posts( $args ); if( count( $orders ) > 0 ) { ?> <table width="100%"> <tr> <th><?php _e( 'Order Id', 'woocommerce' ); ?></th> <th><?php _e( 'Total', 'woocommerce' ); ?></th> <th><?php _e( 'Billing Name', 'woocommerce' ); ?></th> <th><?php _e( 'Status', 'woocommerce' ); ?></th> </tr> <?php foreach ( $orders as $key => $value ) { $order = new WC_Order( $value->ID ); // 校验订单对象有效再输出内容 if ( $order ) { ?> <tr> <td> <?php // 1. 输出订单ID并跳转编辑页 echo '<a href="'. admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) .'" >' . $order->get_order_number() . '</a>'; ?> </td> <td> <?php // 2. 输出格式化后的订单金额 echo wc_price( $order->get_total() ); ?> </td> <td> <?php // 3. 输出账单名(如需展示全名可拼接 get_billing_last_name() 方法) echo esc_html( $order->get_billing_first_name() ); ?> </td> <td> <?php // 4. 输出订单状态 echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?> </td> </tr> <?php // 闭合 if ($order) 判断 } } ?></table> <?php } }
内容的提问来源于stack exchange,提问作者ACE-CM
相关产品推荐
相关产品推荐

