Search code examples
phpwordpresscategoriesarchive

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


I would like to have limit excerpt length 30 characters in echo '<p>' . $category->description . '</p>'; here my code:

<?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' );
    }
?>

How do I add limit excerpt length in echo '<p>' . $category->description . '</p>';?

Thanks,

Shaun.


Solution

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

    Use mb_strimwidth() function

    This will limit the characters, and add add dots if more then 30 characters.