wordpress. character limit on category title using substr

I am using this code. Now i want to add “…” at the end of every category titles with more than 10 characters.’

sample: coconut is the b…

Read More

how to do that?

<a href="' . get_category_link($category->term_id) . '">' . substr($category->cat_name, 0, 10) . ' </a>

Related posts

Leave a Reply

3 comments

  1. You can check the string length first to see that the string is larger than 10 characters:

    <?php
        $current_cat    =   get_query_var('cat');
        $categories     =   get_categories('orderby=id&order=desc&number=16');
        foreach($categories as $category) { ?>
                <div class="latest">
                <?php the_post_thumbnail(array( 160,100 ), array( 'class' => 'primary' )); ?>
                    <img src="domain.com/images/<?php echo $category->category_nicename; ?>.jpg" />
                </div>
                <div class="latest-details"><a href="<?php echo get_category_link($category->term_id); ?>"><?php echo substr($category->cat_name, 0, 10); echo (strlen($category->cat_name) > 10)? "...":""; ?></a>
     <?php } ?>
    

    Here is the manual for strlen(): http://php.net/manual/en/function.strlen.php

  2. if (substr($category->cat_name,0,10) != $category->cat_name)
    {
      $category->cat_name = substr($category->cat_name,0,10);
      $category->cat_name .= '...';
    }
    

    Will do this. Set your output without substr() after this if statement, you can keep $category->cat_name as object

  3. You can use this function:

    function stringLimit($text,$limit){
           $length = strlen($text);
           if($length>$limit){ 
               $finalText= substr($text,0,$limit)."...";} 
               else {$finalText=$text;}
        return $finalText;
        } 
    $text = stringLimit($text,10);
    

    Hope this will help you.