如何限制 $category->archive-products.php WordPress 中的描述的摘录长度?

How to Limit Excerpt Length in $category->description in archive-products.php WordPress?

我想在 echo '<p>' . $category->description . '</p>'; 中将摘录长度限制为 30 个字符,我的代码是:

<?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = true ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );
    $product_categories = get_terms( 'product_category', $cat_args );
        if( !empty($product_categories) ){
            echo '<div class="container">';
            echo '<div class="row">';
            foreach ($product_categories as $key => $category) {
                echo '<div class="col-lg-6">';
                echo '<div class="card">';
                echo '<a href="'.get_term_link($category).'" >';
                $image = get_field('product_category', $category );
                if($image) {
                    echo '<img class="card-img-top" src="' . $image['url'] . '" alt="' . $image['alt'] .'">';
                    } else {
                        echo '<img class="card-img-top" src="/wp-content/uploads/2018/07/placeholder.png">';
                    }
                echo '<h3>' . $category->name . '</h3>';
                //echo $category->name;
                echo '<p>' . $category->description . '</p>';
                echo '<button class="button btn_medium btn_orange btn_squared btn_normal_style" href="'.get_term_link($category).'" >Discover more</button>';
            echo '</a>';
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';
    }
    else {
        // no posts found
        echo wpautop( 'Sorry, no products were found' );
    }
?>

如何在 echo '<p>' . $category->description . '</p>'; 中添加限制摘录长度?

谢谢,

肖恩。

echo '<p>' . mb_strimwidth($category->description, 0, 30, "...") . '</p>'

使用mb_strimwidth()函数

这样会限制字符数,超过30个字符会加点。

您可以使用 sting 函数 substr(),给定的就是您正在寻找的解决方案:

<?php $description = $category->description; ?>

<p><?php echo substr($description ,0,30); ?> </p>