【问题标题】:Limit WooCommerce product title to a specific length (and add '...')将 WooCommerce 产品标题限制为特定长度(并添加“...”)
【发布时间】:2021-03-27 02:21:12
【问题描述】:

我正在尝试限制我们的 WooCommerce 产品标题的字符数,我找到了这个 PHP 代码:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
    if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' ) {
        return substr( $title, 0, 30); // change last number to the number of characters you want
    } else {
        return $title;
    }
}

它有效,但我希望它在每个产品标题的末尾显示“...”。

【问题讨论】:

  • return substr( $title, 0, 30);替换为return substr( $title, 0, 30) . '…';
  • 还有一个问题:如何从短于本代码中允许的最大长度(在这种情况下为 30)的产品标题中删除“...”?

标签: php wordpress woocommerce hook-woocommerce string-length


【解决方案1】:

当产品标题超过特定长度时,您可以使用strlen() php 函数来定位特定产品标题长度以将 附加到缩短的标题:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
    if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
        return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
    } else {
        return $title;
    }
}

代码进入活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

【讨论】:

    【解决方案2】:

    我使用此代码并将字符数更改为 40,但随后进入第 2 行,然后添加到购物车按钮的对齐受到干扰,它与其他产品对齐更改。

    add_filter('the_title', 'shorten_woo_product_title', 10, 2);函数shorten_woo_product_title($title,$id){if(!is_singular(array('product'))&& get_post_type($id)==='product'&& strlen($title)> 30){return substr($title, 0, 30) 。 '……'; // 把最后一个数字改成你想要的字符数 } else { return $title; } }

    【讨论】:

    • 如果您有问题,创建自己的主题或评论与您的​​问题相关的答案会更合适。在您的情况下,您正在寻求与“已接受”答案相关的 CSS 问题的帮助,但与最初的问题(谈论 PHP)无关。就您而言,接受答案的作者永远不会看到您的问题。如果您使用stackoverflow的适当功能来帮助您,您将有更多机会。
    【解决方案3】:

    您可以通过将以下样式属性添加到包含您想要省略的内容的元素来使用 CSS 来做到这一点。这将确保内容始终显示到元素的边缘,而不会溢出。

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    

    这种方法应该比 JS 解决方案性能更高,在实现这样的功能时,如果可能,我总是选择纯 CSS 解决方案,然后再恢复为 Javascript 或在后端修剪字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多