php - 如何在 WooCommerce 类别页面中缩短(截断)长产品标题?

标签 php wordpress woocommerce

我想在 WooCommerce 类别页面中截断带有“...”的较短标题中的长产品标题。如果我是对的,类别页面中的产品将通过“content-product.php”的循环显示。

代码是:

<li<?php echo $class ?>>
<?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

<a href="<?php the_permalink(); ?>">

    <div class="thumbnail">     
        <?php do_action( 'woocommerce_before_shop_loop_item_title' ); ?>

        <?php if ( yiw_get_option( 'shop_show_name' ) ) : ?>
            <strong class="<?php echo $title_position; ?>">
                <?php the_title(); ?>
            </strong>
        <?php endif ?>
    </div>

    <?php do_action( 'woocommerce_after_shop_loop_item_title' ); ?>
</a>

<?php do_action( 'woocommerce_after_shop_loop_item' ); ?>
</li>

我发现了很多 PHP 函数来缩短长字符串(这个看起来很简单 http://shrtnr.us/r0yfwg ),但我无法将函数应用于 the_title()...

如果有人能让我走上正确的道路,我将不胜感激。提前致谢:)

最佳答案

请使用此处给出的以下代码,它工作正常 - shorten-woocommerce-product-titles

只需将以下代码放入主题的 functions.php 即可完成。

    // Automatically shortens WooCommerce product titles on the main shop, category, and tag pages 
// to a specific number of words
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 );

关于php - 如何在 WooCommerce 类别页面中缩短(截断)长产品标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828274/

相关文章:

php - 是否应该在 MySQL 查询中引用用户输入的数字以帮助避免 SQL 注入(inject)攻击?

php - 自定义和添加 woocommerce 模板数据

php - 付款前在结账页面获取订单ID

php - 用于动态显示 WooCommerce 产品类别的嵌套短代码

php - 在字符串中间添加一个字符

css - 我无法覆盖 woocommerce.css

php - 尝试使用 jquery ajax 在文本框输入上提交表单不起作用

php - 比较表中同一列的不同行

php - 从 Laravel-5.7 在 S3 中上传文件时出现 AccessDenied 错误

php - 这个正则表达式有什么作用