首页 > 解决方案 > WooCommerce - 在运输方式标签的(之前)特定字符处插入新行

问题描述

我需要拆分运输方式标签的内容,以便在字符串中的第一个左括号之后插入一个换行符(。下面的示例代码:

<ul id="shipping_method" class="woocommerce-shipping-methods">
   <li>
    <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_cpam" value="CPAM" class="shipping_method">
        <label for="shipping_method_0_cpam">Registered Mail (20-40 days delivery): 
            <span class="woocommerce-Price-amount amount">
                  <span class="woocommerce-Price-currencySymbol">£</span>
            0.00</span>
        </label>                    
   </li>
</ul>

因此,对于所有ul.woocommerce-shipping-methods li label元素,我需要将第一个左括号之后(包括)的任何内容拆分到新行上。这可能吗?

从上面的例子中,结果输出应该是:

Registered Mail
(20-40 days delivery)

如果可以将功能添加到我的子主题functions.php文件或覆盖 WooCommerce 模板来做到这一点,那就太好了。

标签: phpwoocommerce

解决方案


通过添加以下函数以(用新行加上运输标签中的括号来替换字符来解决:

add_filter( 'woocommerce_cart_shipping_method_full_label', 'add_shipping_label_line', 9999, 2 );
   
function add_shipping_label_line( $label, $method ) {
    $new_label = preg_replace( '/\(/', '<br/>(', $label );
    return $new_label;
}

推荐阅读