Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

php - Add shortened description under the product title in WooCommerce archive pages

enter image description here

In Woocommerce archives pages, I should need to display couple of lines from the product description under each product title like it's shown in this image.

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated: This custom function will shorten the product description (to a defined amount of words) and will display it under the title of each product in archive pages as shop:

add_action('woocommerce_after_shop_loop_item_title', 'description_in_shop_loop_item', 3 );
function description_in_shop_loop_item() {
    global $product;

    // HERE define the number of words
    $limit = 10;

    $description = $product->get_description(); // Product description
    // or
    // $description = $product->get_short_description(); // Product short description

    // Limit the words length
    if (str_word_count($description, 0) > $limit) {
        $words = str_word_count($description, 2);
        $pos = array_keys($words);
        $excerpt = substr($description, 0, $pos[$limit]) . '...';
    } else {
        $excerpt = $description;
    }

    echo '<p class="description">'.$excerpt.'</p>';
}

Code goes in function.php file of your active child theme (or active theme).


Or you can have the same thing based on characters length limit:

add_action('woocommerce_after_shop_loop_item_title', 'description_in_shop_loop_item', 3 );
function description_in_shop_loop_item() {
    global $product;

    // HERE define the number of characters
    $limit = 75;

    $description = $product->get_description(); // Product description
    // or
    // $description = $product->get_short_description();  // Product short description

    // Limit the characters length
    if (strlen($description) > $limit) {
        $excerpt = substr($description, 0, $limit) . '...';
    } else {
        $excerpt = $description;
    }

    echo '<p class="description">'.$excerpt.'</p>';
}

Code goes in function.php file of your active child theme (or active theme).

Both functions are tested and works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...