if condition to limit the words in wordpress title

I have written this code to loop through the latest 6 posts on my blog and display them in a special box but there is a slight problem, when i write longer titles the title moves to the next line. I cant increase the width of my title div so I need to write an if condition to show a “…” if the title moves to the next line after lets say 20 characters.

<div id="freshlyWrapper">
<div id="freshlyposts">
<?php
$freshlyIonised = new WP_Query();
$freshlyIonised->query('category_name=FreshlyIonised&showposts=6');
while($freshlyIonised->have_posts()):
$freshlyIonised->the_post();
?>
<div class="freshlyionisedbox"><h3><a style='text-decoration: underline; color: #000;' href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

Related posts

Leave a Reply

5 comments

  1. There is a better way, with CSS:

    DIV.freshlyionisedbox {
        border: 1px solid #000000;
        white-space: nowrap;
        width: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    

    The advantage of this being the semantic content of your page is preserved, and you don’t have to guess at how many characters will fit on the user’s screen in a certain number of pixels.

  2. The substr way:

    $title = "The quick brown fox jumped over the lazy dog.";
    echo strlen($title) > 25 ? substr($title, 0, 25).'...' : $title;
    // The quick brown fox jumpe...
    

    This is what I usually use, to prevent words from cutting:

    function truncate($str, $width, $cutword = false) {
        if (strlen($str) <= $width) return $str;
        list($out) = explode("n", wordwrap($str, $width, "n", $cutword), 2);
        return $out.'...';
    }
    
    $title = "The quick brown fox jumped over the lazy dog.";
    echo truncate($title, 25); 
    // The quick brown fox...
    
    $title = "The quick brown fox";
    echo truncate($title, 25); 
    // The quick brown fox
    
  3. Try substr:

    $title = get_the_title();
    
    if (strlen($title) > 20)
        $title = substr( $title, 0 , 20 ) . "..."; // Limits title to 20 characters.
    

    Implement like so:

    <div id="freshlyWrapper">
    <div id="freshlyposts">
    <?php
        $freshlyIonised = new WP_Query();
        $freshlyIonised->query('category_name=FreshlyIonised&showposts=6');
        while($freshlyIonised->have_posts()):
            $freshlyIonised->the_post();
    
            $title = get_the_title();
    
            if (strlen($title) > 20)
                $title = substr( $title, 0 , 20 ) . "..."; // Limits title to 20 characters.
    ?>
    <div class="freshlyionisedbox">
        <h3><a style='text-decoration: underline; color: #000;' href="<?php the_permalink(); ?>"><?php echo $title; ?></a></h3>