减少 Woocommerce 中的产品长描述

Reduce product long description in Woocommerce

我找到了下面的代码,但它只应用在产品标题下。那么如何才能申请到产品的详细说明。

add_action( 'woocommerce_after_shop_loop_item_title', 'shorten_product_excerpt', 35 );
function shorten_product_excerpt()
{
    global $post;
    $limit = 14;
    $text = $post->post_excerpt;
    if (str_word_count($text, 0) > $limit) {
        $arr = str_word_count($text, 2);
        $pos = array_keys($arr);
        $text = substr($text, 0, $pos[$limit]) . '...';
        // $text = force_balance_tags($text); // may be you dont need this…
    }
    echo '<span class="excerpt"><p>' . $text . '</p></span>';
}

在 Woocommerce 产品单页中,长描述显示在 "description tab" 中。如果您查看 single-product/tabs/description.php 模板的源代码,它使用 the_content() wordpress 函数来显示该长描述。

因此您可以使用 the_content 专用的 Wordpress 过滤器挂钩来减少产品的长描述:

add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
    // Only for single product pages
    if( ! is_product() ) return $content;

    // Set the limit of words
    $limit = 14;

    if (str_word_count($content, 0) > $limit) {
        $arr = str_word_count($content, 2);
        $pos = array_keys($arr);
        $text = '<p>' . substr($content, 0, $pos[$limit]) . '...</p>';
        $content = force_balance_tags($text); // needded
    }
    return $content;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

之前:

之后:

类似: