如何分别限制每个标题的WooCommerce产品标题长度?

时间:2018-01-08 00:57:30

标签: php wordpress woocommerce

在WooCommerce博客页面上有缩略图,我基本上有产品,我希望在3个单词之后切断标题,但其他人在5个单词之后,依此类推。我已将此片段添加到我的functions.php文件中:

function short_woocommerce_product_titles_words( $title, $id ) {
  if ( ( is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
    $title_words = explode(" ", $title);
    if ( count($title_words) > 5 ) { // Kicks in if the product title is longer than 5 words
      // Shortens the title to 5 words and adds ellipsis at the end
      return implode(" ", array_slice($title_words, 0, 5)) . '...';
    } else {
      return $title; // If the title isn't longer than 5 words, it will be returned in its full length without the ellipsis
    }
  } else {
    return $title;
  }
}
add_filter( 'the_title', 'short_woocommerce_product_titles_words', 10, 2 );

完全可以将我的标题限制为最多5个单词,但我不希望每个标题都有。有没有办法在上面的代码之上有一个单独的参数来限制某些标题而不影响其他标题?我认为这有点单调乏味,但商店里没有添加很多新商品(这是一家书店),所以无论如何这都是一次性的事情。

谢谢!

1 个答案:

答案 0 :(得分:0)

在其他情况下,您是否只想切3个单词?

如果这是因为某些单词很长,您可以计算标题上的所有字母,并根据此设置正确的单词数:

$letters_count = strlen($title);
$title_words = explode(" ", $title);

if($letters_count >= 20) {
   $title = implode(" ", array_slice($title_words, 0, 5)) . '...';
}elseif($letters_count >= 30) {
   $title = implode(" ", array_slice($title_words, 0, 3)) . '...';
}

return $title

编辑:

或者如果你想控制它,你可以添加一个带有复选框的元数据箱,让你检查你是否希望产品的标题更短。