如何在WooCommerce购物车和结账页根据所选配送方式显示短代码内容
替换WooCommerce配送方式自定义消息为短代码的实现方案
以下是修改后的完整代码,已将原代码中的固定文本替换为自定义短代码,同时完成中文适配:
// 注册自定义配送提示短代码 add_shortcode('shipping_custom_notice', 'ts_shipping_custom_notice_shortcode'); function ts_shipping_custom_notice_shortcode() { $shipping_postcode = WC()->customer->get_shipping_postcode(); // 可按需修改短代码返回的文本内容 return sprintf(__("提示:您选择的自提配送支持<strong>100%本地直发</strong>,您的配送邮编为<strong>%s</strong>", "woocommerce"), $shipping_postcode); } // 在购物车和结算页的配送区域后添加自定义消息 add_action( 'woocommerce_cart_totals_after_shipping', 'ts_shipping_method_custom_notice' ); add_action( 'woocommerce_review_order_after_shipping', 'ts_shipping_method_custom_notice' ); function ts_shipping_method_custom_notice() { // 替换为需要触发提示的配送方式ID $targeted_shipping_methods = array('local_pickup:3'); // 获取用户当前选择的配送方式 $chosen_methods = WC()->session->get( 'chosen_shipping_methods' ); if ( ! empty( $chosen_methods ) ) { $chosen_method = reset( $chosen_methods ); // 判断用户选择的配送方式是否在目标列表内 if ( in_array( $chosen_method, $targeted_shipping_methods ) ) { echo '<tr class="shipping"> <td colspan="2" style="text-align:center">' . do_shortcode('[shipping_custom_notice]') . '</td> </tr>'; } } }
关键修改说明:
- 新增短代码
shipping_custom_notice,所有自定义文本都集中在短代码函数内,后续修改文案只需调整此处 - 原直接输出文本的部分替换为
do_shortcode('[shipping_custom_notice]'),通过调用短代码渲染内容 - 文本已适配中文语境,可根据业务需求修改短代码函数内的提示文案
内容的提问来源于stack exchange,提问作者user23311381
相关产品推荐
相关产品推荐

