我使用下面的代码自动缩短静态主页主store 、类别和标签页面上的WooCommerce产品标题.我也想为相关产品做同样的事情.我应该在这里为相关产品添加什么条件标签

此代码自动将静态主页主store 、类别和标签页面上的WooCommerce产品标题缩短为设置的字符数

function short_woocommerce_product_titles_chars( $title, $id ) {
    if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
        // Kicks in if the product title is longer than 60 characters 
        if ( strlen( $title ) > 60) {
            // Shortens it to 60 characters and adds ellipsis at the end
            return substr( $title, 0, 60 ) . '...';
        }
    }

    return $title;
}
add_filter( 'the_title', 'short_woocommerce_product_titles_chars', 10, 2 );

推荐答案

以下代码也会将您当前的代码扩展到相关产品:

function shorten_woocommerce_loop_product_titles( $title, $id ) {
    global $woocommerce_loop;

    if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() || ( isset($woocommerce_loop['name'])
    && $woocommerce_loop['name'] === 'related' ) ) && get_post_type( $id ) === 'product' ) {
        $length_threshold = 60; // Here define the desired number of characters max to be displayed

        // If the product title is longer than xx characters 
        if ( strlen( $title ) > $length_threshold ) {
            // Shortens it to xx characters and adds ellipsis at the end
            return substr( $title, 0, $length_threshold ) . '...';
        }
    }
    return $title;
}
add_filter( 'the_title', 'shorten_woocommerce_loop_product_titles', 10, 2 );

代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.

Php相关问答推荐

将一个数字分配到一系列因素中(就像贪婪算法)

如何使用PHP停止foreach循环中的重复项?

输入手写CSV时在PHP中进行日期判断

Symfony/Panther Web抓取不适用于登录后的内容(云功能)

在WooCommerce管理订单列表中显示项目总权重

无法在Laravel/Vue停靠容器中启动MySQL

在内部API请求之后,在响应客户端之前,是否忘记了PHP中的Header()?

PHP原始数据读取引发max_input_vars错误

PHP从响应应用程序json获取文件代码和URL

Laravel:如何展平多维Eager 加载的集合

在PHP中,如何将介于0和1之间(包括0和1)的浮点概率转换为数组索引?

来自POST请求的(无效)json字符串中的奇怪字符(编码问题)

Symfony5:如何在不登录的情况下使API路由可访问?

PHP根据特定索引值从中删除子数组

WooCommerce在购物车项目中复制产品而不增加产品数量

在 WordPress 中将自定义帖子类型永久链接设置为 root

安装 Herd 并返回 Valet 后为 502

htaccess 无限循环问题

Laravel 自定义中间件:ERR_TOO_MANY_REDIRECTS

使用 PHP 有条件地使用关键字 Twilio Programmable SMS