php - 如何限制 woocommerce 中相关产品的标题长度

标签 php wordpress loops woocommerce product

我使用以下代码自动缩短静态主页主商店、类别和标签页面上的 WooCommerce 产品标题。我也想对相关产品这样做。我应该在此处为相关产品添加什么条件标签

此代码会自动将静态主页主商店、类别和标签页面上的 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 );

代码位于子主题的functions.php 文件中(或插件中)。经过测试并有效。

关于php - 如何限制 woocommerce 中相关产品的标题长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76930842/

相关文章:

php - PHP 中特定的 JSON 格式

php - 工具集表中的第一行具有黑色背景

php - 如何以编程方式将 ACF 组添加到 Wordpress 的后端?

java - PaintComponent 执行了两次

PHP 从所有 MYSQL 结果中选择并标记最近的条目

windows - 批处理文件 : Copy files to all subfolders

javascript - OnClick 按钮仅给出 ajax jquery php mysqli 中的第一行值

php - 我应该如何将我的 mysql 数据库设置为我的 php 文档模板?

php - 有什么关于 php 代码的想法吗?

javascript - Google Analytics(分析)中的自定义指标/维度不起作用