• Hello,

    I have searched far and wide in the WP Support Forums for a solution to my issue, but I have yet to find one. Hopefully someone can help.

    I am using the following code to display a list of recent posts in a specific location on my site:

    <?php
    	$recent_posts = wp_get_recent_posts();
    	foreach( $recent_posts as $recent ){
    		echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
    	}
    ?>

    The list of posts displays fine, but what I would like to do is give the post_title a character limit, i.e. a post with the title “Really really really really long title” would display as “Really really…”, or whatever the character limit is.

    Anyhow, I have found ways to truncate or limit the character limit of the_title and get_the_title across the entire site, but I just cannot seem to find a way to truncate the “post_title” in this specific piece of code.

    Any help would be greatly appreciated.

    Thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator t-p

    (@t-p)

    You can try this:

    <?php
    	$recent_posts = wp_get_recent_posts();
    	foreach( $recent_posts as $recent ){
    
    $thetitle = $recent["post_title"]; /* or you can use get_the_title() */
    $getlength = strlen($thetitle);
    $thelength = 25; // enter length here
    echo substr($thetitle, 0, $thelength);
    
    		echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   substr($thetitle, 0, $thelength).'</a>'
               . if ($getlength > $thelength) echo "..." . '</li> ';
    	}
    ?>

    Modified code stolen from WPbeginner ??

    Thread Starter Benjamin

    (@benleetaylor)

    Keith,

    Thanks for your help! I had to tweak that code a little bit, but it’s working perfectly for me now. Here’s what I ended up with:

    <?php
    $recent_posts = wp_get_recent_posts();
    foreach( $recent_posts as $recent ){
    $thetitle = $recent["post_title"];
    $getlength = strlen($thetitle);
    $thelength = 10;
    echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .
    substr($thetitle, 0, $thelength).'</a>';
    if ($getlength > $thelength) echo "..." . '</li> ';}
    ?>

    Awesome!! because I hate posting code. I’ve become quite reliant on the color coding available in my code editor.

    Glad it’s working ??

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Truncate post_title text in Recent Posts’ is closed to new replies.