在 Woocommerce 产品标题中添加换行符

Add a line break in Woocommerce Product Titles

假设我的产品标题是:

Brown Colored Leather Shoes

但是根据我的列宽,标题看起来像这样:

Brown Colored Leather
Shoes

我知道可以进行字符替换,使后端的 "|" 变成换行符 <br/>。但是我不知道怎么办。

我希望它看起来像这样

Brown Colored
Leather Shoes

我找到了这些参考文献:

是否可以为 WC 产品长标题添加换行符?

2020 修订版 - 仍然适用于 Wordpress 5.5.1 和 WooCommerce 4.4.1

使用挂接到 the_title 过滤器挂钩中的自定义函数将完成这项工作(用 <br> 中的 <br> 替换竖线字符 |产品标题):

add_filter( 'the_title', 'custom_product_title', 10, 2 );
function custom_product_title( $title, $post_id ){
    $post_type = get_post_field( 'post_type', $post_id, true ); 

    if( in_array( $post_type, array( 'product', 'product_variation') ) ) {
        $title = str_replace( '|', '<br/>', $title ); // we replace "|" by "<br>"
    }
    return $title;
}

代码进入您的活动 child 主题(或主题)的 function.php 文件或任何插件文件。

代码已在 Woocommerce 3+ 上测试并有效。

Now you can target different product pages with the WC conditionals tags as is_product(), is_shop(), is_product_category() or is_product_tag() (and many others)

2019 年 11 月使用 Wordpress 5.2.4 的完整答案:

//ADD LINE BREAK 
add_filter( 'the_title', 'custom_the_title', 10, 2 );
function custom_the_title( $title, $post_id ) {
    $post_type = get_post_field( 'post_type', $post_id, true );
    if( $post_type == 'product' || $post_type == 'product_variation' )
        $title = str_replace( '|', '<br/>', $title ); // we replace '|' by '<br>'
    return $title;
}

感谢 LoicTheAztec 和 Coes

如果有人喜欢,我有一个 JS 解决方案,只需添加到自定义 js 中即可:

if (document.querySelector('.product_title') !== null) {
var str = document.querySelector('.product_title').innerHTML; 
var res = str.replace("|", "<br/>");
document.querySelector('.product_title').innerHTML = res;
}

如果您在 functions.php

中想出解决方法时需要解决方法,这可能会有所帮助