如何开发基于WooCommerce订单状态输出自定义内容的shortcode功能
WooCommerce订单状态自定义短代码实现方案
现有代码问题说明
- 短代码回调参数规则错误:WordPress原生短代码回调的固定入参为
($atts, $content = null),第二个参数不是订单ID,订单ID需要通过短代码属性传递,或者在订单详情页从全局变量自动获取。 - 缺少订单合法性校验:如果传入无效订单ID,直接调用
$order->has_status()会抛出PHP致命错误。 - 无兜底默认返回值,未匹配到对应状态时会返回空字符串。
- 仅返回数字标识,不支持自定义消息配置,拓展性弱。
优化后可直接使用的实现代码
add_shortcode( 'order_status_custom', 'wpc_orderstatus_shortcode'); function wpc_orderstatus_shortcode( $atts ) { // 短代码默认属性配置,支持自定义各状态消息、手动指定订单ID $atts = shortcode_atts( [ 'order_id' => get_query_var( 'order-id', 0 ), 'pending_msg' => '订单待支付', 'processing_msg' => '订单处理中', 'on_hold_msg' => '订单已暂停', 'completed_msg' => '订单已完成', 'default_msg' => '订单状态未知' ], $atts ); $order_id = absint( $atts['order_id'] ); $order = wc_get_order( $order_id ); // 订单不存在直接返回默认提示 if ( ! $order ) { return esc_html( $atts['default_msg'] ); } // 按状态匹配返回对应消息 if ( $order->has_status('completed') ) { $data = $atts['completed_msg']; } elseif( $order->has_status('on-hold') ){ $data = $atts['on_hold_msg']; } elseif( $order->has_status('processing') ){ $data = $atts['processing_msg']; } elseif( $order->has_status('pending') ){ $data = $atts['pending_msg']; } else { $data = $atts['default_msg']; } return esc_html( $data ); }
使用方法
- 手动指定订单ID调用:
[order_status_custom order_id="123" completed_msg="您的订单已发货,请留意物流信息"],可按需单独配置每个状态的自定义消息 - 订单详情页自动识别调用:直接插入
[order_status_custom]即可自动读取当前页面的订单ID匹配对应状态
内容的提问来源于stack exchange,提问作者cabral279
相关产品推荐
相关产品推荐

