【问题标题】:Hiding middle-dash in mini-cart (theme functions.php)在迷你购物车中隐藏中间破折号(主题functions.php)
【发布时间】:2016-09-14 08:28:28
【问题描述】:

我目前正在准备基于 Woocommerce 的在线商店,但我对迷你购物车的外观有疑问。每当特定产品的名称太长时,都会导致迷你购物车出现问题(不适合 .cart_wrapper)。

我决定隐藏(重复的)产品名称中最不重要的元素。我使用了以下代码:

function wpse_remove_shorts_from_cart_title( $product_name ) {
    $product_name = str_ireplace( 'premium', '', $product_name );
    $product_name = str_ireplace( 'standard', '', $product_name );

    return $product_name;
}
add_filter( 'woocommerce_cart_item_name', 'wpse_remove_shorts_from_cart_title' );

而且效果很好。以产品名称为例:

Car Carpet VW (1999-2001) - PREMIUM

我明白了:

Car Carpet VW (1999-2001) -

现在对我来说问题是出现在产品名称末尾的中间破折号。

我无法使用上述方法删除它,因为通过这种方式,它还删除了括号内的中间破折号(分隔年份或生产的那个)。

由于我对 PHP 的了解非常基础 - 我向你提出一个问题 - 是否有任何标签可以让我隐藏名称末尾的中间破折号,同时保留现有的中间破折号括号。

我该怎么做?

【问题讨论】:

    标签: php wordpress woocommerce cart character-trimming


    【解决方案1】:

    是的,可以使用原生 php 函数 rtrim()。你会这样使用它:

    <?php
        $string1 = 'Car Carpet VW (1999-2001) - PREMIUM';
        $string2 = 'Car Carpet VW (1999-2001) -';
        $string1 = rtrim($string1, ' -');
        $string2 = rtrim($string2, ' -');
        echo '$string1: '.$string1.'<br>'; // displays "Car Carpet VW (1999-2001) - PREMIUM"
        echo '$string2: '.$string2.'<br>'; // displays "Car Carpet VW (1999-2001)"
    ?>
    

    参考:PHP function rtrim()

    【讨论】:

      【解决方案2】:

      为什么不直接用 PREMIUM 或 STANDARD 替换功能替换呢?

      像这样:

      function wpse_remove_shorts_from_cart_title( $product_name ) {
          $product_name = str_replace( '- premium', '', $product_name );
          $product_name = str_replace( '- standard', '', $product_name );
      
          return $product_name;
      }
      add_filter( 'woocommerce_cart_item_name', 'wpse_remove_shorts_from_cart_title' );
      

      我也会使用str_replace() 而不是str_ireplace(),因为str_replace() 不区分大小写。

      【讨论】:

      • 我现在觉得很愚蠢,因为它确实有效。非常感谢。
      猜你喜欢
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多