【问题标题】:Add a line break in Woocommerce Product Titles在 Woocommerce 产品标题中添加换行符
【发布时间】:2018-03-17 21:36:27
【问题描述】:

假设我的产品标题是:

棕色皮鞋

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

棕色皮革
鞋子

我知道可以进行字符替换,以便后端中的"|" 成为换行符<br/>。但我不知道怎么做。

我希望它看起来像这样

棕色
皮鞋

我找到了这些参考资料:

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

【问题讨论】:

    标签: php wordpress woocommerce title product


    【解决方案1】:

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

    使用挂在 the_title 过滤器钩子中的这个自定义函数可以完成这项工作(将产品标题中的管道字符 | 替换为 <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;
    }
    

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

    代码在 Woocommerce 3+ 上经过测试并且可以运行。

    现在您可以使用 WC 条件标签定位不同的产品页面,如 is_product()is_shop()is_product_category()is_product_tag()(以及许多其他标签)...

    【讨论】:

    • 不。我一定是做错了什么:(imgur.com/ki1Avuw 顺便添加到我的孩子主题中。
    • :( 是的,我看到它对你有用。你看到我的屏幕截图有什么问题吗?感谢您抽出宝贵时间回答。
    • 好的,我让这个做点什么!
    • 解析错误:语法错误,意外的 ''
      '' (T_CONSTANT_ENCAPSED_STRING),在 /home/...../functions.php 第 450 行需要 ',' 或 ')'
    • 我明白了!问题是您的代码中的一个字符。正确答案是//ADD LINE BREAK 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( '|', '&lt;br/&gt;', $title ); // we replace '|' by '&lt;br&gt;': return $title; } 谢谢谢谢!!当我复制您的代码时,它创建了一个 OBJ 角色。这里imgur.com/8expPVQ
    【解决方案2】:

    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

    【讨论】:

      【解决方案3】:

      如果有人愿意,我有一个 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中想出一种解决方法时需要解决方法,这可能会有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 2018-12-14
        • 1970-01-01
        相关资源
        最近更新 更多